protected virtual void WriteTOC(List<PdfContentParameter> contents, PdfWriter writer, Document document) { document.NewPage(); PdfPTable t = new PdfPTable(2); t.WidthPercentage = 100; t.SetWidths(new float[] { 98f, 2f }); t.TotalWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin); t.AddCell(new PdfPCell( new Phrase(GlobalStringResource.TableOfContents, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16)) ) { Colspan = 2, Border = Rectangle.NO_BORDER, PaddingBottom = 25 }); foreach (PdfContentParameter item in contents) { if (!string.IsNullOrEmpty(item.Header)) { t.AddCell( new PdfPCell( new Phrase(item.Header, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8) ) ) { Border = Rectangle.NO_BORDER, NoWrap = false, FixedHeight = 15, } ); PdfPCell templateCell = new PdfPCell(Image.GetInstance(item.Template)); templateCell.HorizontalAlignment = Element.ALIGN_RIGHT; templateCell.Border = Rectangle.NO_BORDER; t.AddCell(templateCell); } } float docHeight = document.PageSize.Height - heightOffset; document.Add(t); }
protected internal virtual PdfObject GetSpotObject(PdfWriter writer) { PdfArray array = new PdfArray(PdfName.SEPARATION); array.Add(name); PdfFunction func = null; if (altcs is ExtendedColor) { int type = ((ExtendedColor)altcs).Type; switch (type) { case ExtendedColor.TYPE_GRAY: array.Add(PdfName.DEVICEGRAY); func = PdfFunction.Type2(writer, new float[]{0, 1}, null, new float[]{0}, new float[]{((GrayColor)altcs).Gray}, 1); break; case ExtendedColor.TYPE_CMYK: array.Add(PdfName.DEVICECMYK); CMYKColor cmyk = (CMYKColor)altcs; func = PdfFunction.Type2(writer, new float[]{0, 1}, null, new float[]{0, 0, 0, 0}, new float[]{cmyk.Cyan, cmyk.Magenta, cmyk.Yellow, cmyk.Black}, 1); break; default: throw new Exception(MessageLocalization.GetComposedMessage("only.rgb.gray.and.cmyk.are.supported.as.alternative.color.spaces")); } } else { array.Add(PdfName.DEVICERGB); func = PdfFunction.Type2(writer, new float[]{0, 1}, null, new float[]{1, 1, 1}, new float[]{(float)altcs.R / 255, (float)altcs.G / 255, (float)altcs.B / 255}, 1); } array.Add(func.Reference); return array; }
//重写 关闭一个页面时 public override void OnEndPage(PdfWriter writer, Document document) { try { Font font = new Font(basefont, defaultFontSize); Phrase head = new Phrase(header, font); PdfContentByte cb = writer.DirectContent; //页眉显示的位置 ColumnText.ShowTextAligned(cb, Element.ALIGN_RIGHT, head, document.Right - 10 + document.LeftMargin, document.Top + 10, 0); if (PAGE_NUMBER) { Phrase footer = new Phrase("第 " + writer.PageNumber + " / " + " "+" 頁", font); cb = writer.DirectContent; //tpl = cb.CreateTemplate(100, 100); //模版 显示总共页数 cb.AddTemplate(tpl, document.Left / 2 + document.Right / 2 , document.Bottom - 10);//调节模版显示的位置 //页脚显示的位置 ColumnText.ShowTextAligned(cb, Element.ALIGN_RIGHT, footer, document.Left / 2+document.Right/ 2+23, document.Bottom - 10, 0); } } catch (Exception ex) { throw new Exception("HeaderAndFooterEvent-->OnEndPage-->" + ex.Message); } }
public override void OnOpenDocument(PdfWriter writer, Document document) { printTime = DateTime.Now; baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); pdfContent = writer.DirectContent; pageNumberTemplate = pdfContent.CreateTemplate(50, 50); }
/** * Creates a title layer. A title layer is not really a layer but a collection of layers * under the same title heading. * @param title the title text * @param writer the <CODE>PdfWriter</CODE> * @return the title layer */ public static PdfLayer CreateTitle(String title, PdfWriter writer) { if (title == null) throw new ArgumentNullException("Title cannot be null."); PdfLayer layer = new PdfLayer(title); writer.RegisterLayer(layer); return layer; }
/** * Creates a title layer. A title layer is not really a layer but a collection of layers * under the same title heading. * @param title the title text * @param writer the <CODE>PdfWriter</CODE> * @return the title layer */ public static PdfLayer CreateTitle(String title, PdfWriter writer) { if (title == null) throw new ArgumentNullException(MessageLocalization.GetComposedMessage("title.cannot.be.null")); PdfLayer layer = new PdfLayer(title); writer.RegisterLayer(layer); return layer; }
internal PdfReaderInstance(PdfReader reader, PdfWriter writer) { this.reader = reader; this.writer = writer; file = reader.SafeFile; myXref = new int[reader.XrefSize]; }
/** * Adds the header and the footer. * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public override void OnEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.GetBoxSize("art"); switch (writer.PageNumber % 2) { case 0: ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_RIGHT, header[0], rect.Right, rect.Top, 0 ); break; case 1: ColumnText.ShowTextAligned( writer.DirectContent, Element.ALIGN_LEFT, header[1], rect.Left, rect.Top, 0 ); break; } ColumnText.ShowTextAligned( writer.DirectContent, Element.ALIGN_CENTER, new Phrase(String.Format("page {0}", pagenumber)), (rect.Left + rect.Right) / 2, rect.Bottom - 18, 0 ); }
/** * Creates a file specification of type URL. * @param writer the <CODE>PdfWriter</CODE> * @param url the URL * @return the file specification */ public static PdfFileSpecification Url(PdfWriter writer, String url) { PdfFileSpecification fs = new PdfFileSpecification(); fs.writer = writer; fs.Put(PdfName.FS, PdfName.URL); fs.Put(PdfName.F, new PdfString(url)); return fs; }
public virtual ColorDetails[] GetColorantDetails(PdfWriter writer) { if (altColorDetails == null && this.altcs is ExtendedColor && ((ExtendedColor) this.altcs).Type == ExtendedColor.TYPE_LAB) { altColorDetails = writer.AddSimple(((LabColor) altcs).LabColorSpace); } return new ColorDetails[] {altColorDetails}; }
/** * Initialize one of the headers, based on the chapter title; * reset the page number. * @see com.itextpdf.text.pdf.PdfPageEventHelper#onChapter( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, float, * com.itextpdf.text.Paragraph) */ public override void OnChapter( PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { header[1] = new Phrase(title.Content); pagenumber = 1; }
protected void initFile(bool bBlackAndWhite = false) { m_doc = new Document(); string folder = Settings.Default["pdffolder"].ToString() + m_strFolder; System.IO.Directory.CreateDirectory(folder ); string fileName = folder + "/"+m_strTitle; if (bBlackAndWhite) fileName += "BW.pdf"; else fileName += ".pdf"; m_writer = PdfWriter.GetInstance(m_doc, new System.IO.FileStream(fileName, System.IO.FileMode.Create)); m_doc.Open(); m_fSmall = new iTextSharp.text.Font(); m_fSmall.Size = 10; m_fBig = new iTextSharp.text.Font(); m_fBig.Size = 40; m_fBig.Color = bBlackAndWhite ? BaseColor.BLACK : getNextColor(); // m_fBig.SetStyle("bold"); m_fNorm = new iTextSharp.text.Font(); m_fNorm.Size = 20; m_fNorm.Color = new BaseColor(m_colorText); m_doc.Add(new Paragraph("Name:____________________________________________ Date:______________"/*, fSmall*/)); m_doc.Add(new Paragraph(m_strTitle, m_fBig)); m_doc.Add(new Paragraph(" ")); }
/// <summary> /// Fires when a page is finished, just before being written to the document. /// </summary> /// <param name="writer">PdfWriter</param> /// <param name="document">PDF Document</param> /// <param name="columnCellsSummaryData">List of all rows summaries data</param> public void PageFinished(PdfWriter writer, Document document, IList<SummaryCellData> columnCellsSummaryData) { var footerTable = AddPageFooter(new FooterData { PdfDoc = document, PdfWriter = writer, SummaryData = columnCellsSummaryData, CurrentPageNumber = writer.PageNumber, TotalPagesCountImage = _totalPageCountImage }); var table = new PdfGrid(1) { RunDirection = (int)FooterProperties.RunDirection, WidthPercentage = FooterProperties.TableWidthPercentage }; var tableCell = new PdfPCell(footerTable) { Border = 0 }; table.AddCell(tableCell); var page = document.PageSize; table.SetTotalWidth(new[] { page.Width - document.LeftMargin - document.RightMargin }); table.WriteSelectedRows( rowStart: 0, rowEnd: -1, xPos: document.LeftMargin, yPos: document.BottomMargin - FooterProperties.SpacingBeforeTable, canvas: writer.DirectContent); }
public override void OnOpenDocument(PdfWriter writer, Document document) { base.OnOpenDocument(writer, document); font = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); dc = writer.DirectContent; tpl = dc.CreateTemplate(50, 50); }
// we override the onOpenDocument method public override void OnOpenDocument(PdfWriter writer, Document document) { _bf = _normalFont.GetCalculatedBaseFont(false); _cb = writer.DirectContent; _ct = new ColumnText(_cb); base.OnOpenDocument(writer, document); }
public override void OnEndPage(PdfWriter writer, Document document) { ColumnText.ShowTextAligned( writer.DirectContentUnder, Element.ALIGN_CENTER, new Phrase("FOOBAR FILM FESTIVAL", FONT), 297.5f, 421, writer.PageNumber % 2 == 1 ? 45 : -45 ); }
public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); int pageN = writer.PageNumber; String text = "Page " + pageN + " of "; float len = _bf.GetWidthPoint(text, 8); Rectangle pageSize = document.PageSize; _cb.SetRGBColorFill(100, 100, 100); _cb.BeginText(); _cb.SetFontAndSize(_bf, 8); _cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30)); _cb.ShowText(text); _cb.EndText(); _cb.AddTemplate(_template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30)); _cb.BeginText(); _cb.SetFontAndSize(_bf, 8); _cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Printed On " + _printTime.ToString(), pageSize.GetRight(40), pageSize.GetBottom(30), 0); _cb.EndText(); }
internal PdfPatternPainter(PdfWriter wr, Color defaultColor) : this(wr) { stencil = true; if (defaultColor == null) this.defaultColor = new Color(System.Drawing.Color.Gray); else this.defaultColor = defaultColor; }
private void InitializeDocument() { MemoryStream baos = new MemoryStream(); document = new Document(); writer = PdfWriter.GetInstance(document, baos); document.Open(); }
public override void OnEndPage(PdfWriter writer, Document document) { if (writer == null) throw new ArgumentNullException("writer"); if (document == null) throw new ArgumentNullException("document"); ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(this.config.Header1, new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD)), document.PageSize.Width / 2, document.PageSize.Height - 36, 0); ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(this.config.Header2, new Font(Font.FontFamily.HELVETICA, 14, Font.NORMAL, BaseColor.GRAY)), document.PageSize.Width / 2, document.PageSize.Height - 56, 0); writer.DirectContent.SetLineWidth(1); writer.DirectContent.SetColorFill(BaseColor.BLACK); writer.DirectContent.SetColorStroke(BaseColor.BLACK); writer.DirectContent.MoveTo(document.LeftMargin, document.PageSize.Height - document.TopMargin + 15); writer.DirectContent.LineTo(document.PageSize.Width - document.RightMargin, document.PageSize.Height - document.TopMargin + 15); writer.DirectContent.Stroke(); writer.DirectContent.MoveTo(document.LeftMargin, document.BottomMargin - 15); writer.DirectContent.LineTo(document.PageSize.Width - document.RightMargin, document.BottomMargin - 15); writer.DirectContent.Stroke(); // footer left 1 ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_LEFT, new Phrase(this.config.FooterLeft1, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)), document.LeftMargin, document.BottomMargin - 30, 0); // footer left 2 ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_LEFT, new Phrase(this.config.FooterLeft2, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)), document.LeftMargin, document.BottomMargin - 42, 0); // footer right 1 ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_RIGHT, new Phrase(this.config.FooterRight1, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)), document.PageSize.Width - document.RightMargin, document.BottomMargin - 30, 0); // footer right 2 ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_RIGHT, new Phrase(this.config.FooterRight2, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)), document.PageSize.Width - document.RightMargin, document.BottomMargin - 42, 0); base.OnEndPage(writer, document); }
public override void OnOpenDocument(PdfWriter writer, Document document) { total = writer.DirectContent.CreateTemplate(100, 100); total.BoundingBox = new Rectangle(-20, -20, 100, 100); helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); }
public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); Rectangle pageSize = document.PageSize; int pageN = writer.PageNumber; String text = "Page " + pageN + "/"; float len = bf.GetWidthPoint(text, 8); cb.SetRGBColorFill(0, 0, 0); // Line separated fotter from rest of sheet cb.MoveTo(50, pageSize.Bottom + 60); cb.LineTo(pageSize.Right - 50, pageSize.Bottom + 60); cb.SetLineWidth(0.75f); cb.Fill(); cb.Stroke(); cb.BeginText(); cb.SetFontAndSize(gf, 8); cb.SetTextMatrix(pageSize.GetLeft(((pageSize.Width - 80) / 2) + len), pageSize.GetBottom(50)); cb.ShowText(text); cb.EndText(); cb.AddTemplate(template, pageSize.GetLeft(((pageSize.Width - 80) / 2) + len + len - 2), pageSize.GetBottom(50)); cb.BeginText(); cb.SetFontAndSize(gf, 8); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "generated on Ticketing System", pageSize.GetRight(50), pageSize.GetBottom(50), 0); cb.EndText(); }
public override void Close(PdfWriter writer) { base.Close(writer); bool ok = false; IXmpMeta xmpMeta = writer.XmpWriter.XmpMeta; try { String docFileName = xmpMeta.GetPropertyString(PdfAXmpWriter.zugferdSchemaNS, PdfAXmpWriter.zugferdDocumentFileName); foreach (PdfFileSpecification attachment in attachments) { if (docFileName.Equals(attachment.GetAsString(PdfName.UF).ToString())) { PdfName relationship = attachment.GetAsName(PdfName.AFRELATIONSHIP); if (!AFRelationshipValue.Alternative.Equals(relationship)) { attachments.Clear(); throw new PdfAConformanceException(attachment, MessageLocalization.GetComposedMessage("afrelationship.value.shall.be.alternative")); } ok = true; break; } } } catch (Exception e) { attachments.Clear(); throw e; } attachments.Clear(); if (!ok) { throw new PdfAConformanceException(xmpMeta, MessageLocalization.GetComposedMessage("zugferd.xmp.schema.shall.contain.attachment.name")); } }
public override void OnEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.DirectContent; cb.SaveState(); string text = "Page " + writer.PageNumber + " of "; float textBase = document.Bottom - 20; float textSize = 12; //helv.GetWidthPoint(text, 12); cb.BeginText(); cb.SetFontAndSize(helv, 12); if ((writer.PageNumber % 2) == 1) { cb.SetTextMatrix(document.Left, textBase); cb.ShowText(text); cb.EndText(); cb.AddTemplate(total, document.Left + textSize, textBase); } else { float adjust = helv.GetWidthPoint("0", 12); cb.SetTextMatrix(document.Right - textSize - adjust, textBase); cb.ShowText(text); cb.EndText(); cb.AddTemplate(total, document.Right - adjust, textBase); } cb.RestoreState(); }
/** * * @param writer * @param key * @param obj1 */ static public void CheckPdfAConformance(PdfWriter writer, int key, Object obj1) { if (writer == null || !writer.IsPdfIso()) return; switch (key) { case PdfIsoKeys.PDFISOKEY_FONT: if (!((BaseFont)obj1).IsEmbedded()) throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont) obj1).PostscriptFontName)); break; case PdfIsoKeys.PDFISOKEY_IMAGE: PdfImage image = (PdfImage)obj1; if (image.Get(PdfName.SMASK) != null) throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.smask.key.is.not.allowed.in.images")); break; case PdfIsoKeys.PDFISOKEY_GSTATE: PdfDictionary gs = (PdfDictionary)obj1; PdfObject obj = gs.Get(PdfName.BM); if (obj != null && !PdfGState.BM_NORMAL.Equals(obj) && !PdfGState.BM_COMPATIBLE.Equals(obj)) throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("blend.mode.1.not.allowed", obj.ToString())); obj = gs.Get(PdfName.CA); double v = 0.0; if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0) throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v)); obj = gs.Get(PdfName.ca_); v = 0.0; if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0) throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v)); break; case PdfIsoKeys.PDFISOKEY_LAYER: throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("layers.are.not.allowed")); default: break; } }
public override void OnEndPage(PdfWriter writer, Document document) { PdfPTable footer = new PdfPTable(3); footer.SetWidths(new float[] { 88f, 7f, 5f }); footer.WidthPercentage = 100; footer.TotalWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin); PdfPCell emptycell = new PdfPCell(); emptycell.Border = 0; footer.AddCell(emptycell); Chunk text = new Chunk(string.Format(GlobalStringResource.PageOfFooter, document.PageNumber), FontFactory.GetFont(FontFactory.HELVETICA, 8)); PdfPCell footerCell = new PdfPCell(new Phrase(text)); footerCell.Border = 0; footerCell.HorizontalAlignment = Element.ALIGN_RIGHT; footer.AddCell(footerCell); PdfPCell cell = new PdfPCell(iTextSharp.text.Image.GetInstance(total)); cell.Border = 0; cell.HorizontalAlignment = Element.ALIGN_LEFT; footer.AddCell(cell); footer.WriteSelectedRows(0, -1, 50, (document.BottomMargin - 10), writer.DirectContent); }
internal PdfPatternPainter(PdfWriter wr, BaseColor defaultColor) : this(wr) { stencil = true; if (defaultColor == null) this.defaultColor = BaseColor.GRAY; else this.defaultColor = defaultColor; }
public override void OnStartPage(PdfWriter writer, Document document) { PdfPTable headerTable = new PdfPTable(1); headerTable.AddCell(new Phrase("Header")); WriteTable(writer.DirectContent, headerTable, new Rectangle(0, document.PageSize.Height - 50f, document.PageSize.Width, document.PageSize.Height)); }
public string SurveyHTMLToPdf(string HTML, string FileName, long WorkAssignmentId) { GlobalAdminManager objM = new GlobalAdminManager(); FileName = FileName.Replace(' ', '+').Replace('/', '@');//Here @ char replace due to '/' encrypt id it break the URL to open file in HTMLToPDF string waterMarkSurveyFilename = "eTrac" + FileName + ".pdf"; string HostingPrefix = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["hostingPrefix"]); var fileName = System.Web.HttpContext.Current.Server.MapPath("~/Content/eMaintenance/SurveyDownload/") + FileName + ".pdf"; var objData = objM.GetDataForRendringHTML(WorkAssignmentId); //---------------------------- Document doc = new Document(PageSize.A4, 30f, 30f, 40f, 30f); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.CreateNew)); doc.Open(); try { //var content = writer.DirectContent; //var pageBorderRect = new iTextSharp.text.Rectangle(doc.PageSize); //pageBorderRect.Left += doc.LeftMargin; //pageBorderRect.Right -= doc.RightMargin; //pageBorderRect.Top -= doc.TopMargin; //pageBorderRect.Bottom += doc.BottomMargin; //content.SetColorStroke(BaseColor.BLACK); //content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height); //content.Stroke(); //Logo string imageURL = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo-etrac.png"); iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL); jpg.Alignment = 3; jpg.SpacingBefore = 30f; jpg.ScaleToFit(80f, 60f); jpg.SpacingBefore = 10f; jpg.SpacingAfter = 1f; doc.Add(jpg); Paragraph objFormName = new Paragraph("Customer Assistance Survey Form"); objFormName.Alignment = 3; objFormName.SpacingBefore = 3f; objFormName.SpacingAfter = 3f; objFormName.IndentationLeft = 3f; doc.Add(objFormName); StyleSheet css = new StyleSheet(); css.LoadTagStyle("body", "face", "Times-Roman"); css.LoadTagStyle("body", "font", "Times"); css.LoadTagStyle("body", "size", "11pt"); css.LoadTagStyle("body", "color", "#000"); foreach (IElement element in HTMLWorker.ParseToList( new StringReader(HTML), css)) { doc.Add(element); } var font1 = FontFactory.GetFont("Times-Roman", 11, Font.NORMAL, BaseColor.BLACK); PdfPTable table = new PdfPTable(2); PdfPCell cell = new PdfPCell(new Phrase("Customer Name: " + StringExtensionMethods.ToTitleCase(objData.CustomerName), font1)); cell.Colspan = 1; cell.Border = 0; cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right table.AddCell(cell); cell = new PdfPCell(new Phrase("Employee Name: " + StringExtensionMethods.ToTitleCase(objData.AssignedFirstName) + ' ' + StringExtensionMethods.ToTitleCase(objData.AssignedLastName), font1)); cell.Colspan = 1; cell.Border = 0; cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right table.AddCell(cell); doc.Add(table); } catch (Exception) { throw; } finally { doc.Close(); // Watermark code string watermarkLoc = System.Web.HttpContext.Current.Server.MapPath("~/Images/eTrac380-light.png"); PdfReader pdfReader = new PdfReader(fileName); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(fileName.Replace(FileName + ".pdf", waterMarkSurveyFilename), FileMode.Create)); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(watermarkLoc); var pageSize = pdfReader.GetPageSizeWithRotation(1); var x = pageSize.Width / 2 - img.ScaledWidth / 2; var y = pageSize.Height / 2 - img.ScaledHeight / 2; img.SetAbsolutePosition(x, y); //img.ScaleToFit(100f,120f); PdfContentByte waterMark; for (int page = 1; page <= pdfReader.NumberOfPages; page++) { waterMark = pdfStamper.GetUnderContent(page); waterMark.AddImage(img); } pdfStamper.FormFlattening = true; pdfStamper.Close(); pdfReader.Close(); //delete old file. No more need of that file. System.IO.File.Delete(fileName); } ////Render PlaceHolder to temporary stream //System.IO.StringWriter stringWrite = new StringWriter(); //System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); //StringReader reader = new StringReader(HTML); ////Create PDF document //Document doc = new Document(PageSize.A4); //HTMLWorker parser = new HTMLWorker(doc); //PdfWriter.GetInstance(doc, new FileStream(fileName, //FileMode.Create)); //doc.Open(); ///********************************************************************************/ //var interfaceProps = new Dictionary<string, Object>(); //var ih = new ImageHander() { BaseUri = Request.Url.ToString() }; //interfaceProps.Add(HTMLWorker.IMG_PROVIDER, ih); //foreach (IElement element in HTMLWorker.ParseToList( //new StringReader(HTML), null)) //{ // doc.Add(element); //} //doc.Close(); //Response.Clear(); //Response.Buffer = true; //Response.ContentType = "application/pdf"; //Response.AddHeader("content-disposition", "attachment;filename=" + FileName); // to open file prompt Box open or Save file //Response.Charset = ""; //Response.Cache.SetCacheability(HttpCacheability.NoCache); //Response.WriteFile(fileName); //Response.End(); //return FileName; commented bcoz for wtermark we need tosave same file name in db return(waterMarkSurveyFilename); }
protected void btnExportPdf_Click(object sender, EventArgs e) { gridViewDocumentos.AllowPaging = false; BindData(); Document doc = new Document(PageSize.LETTER); doc.AddTitle("Estado de Cuenta"); doc.AddCreator("E&E Integra"); System.IO.MemoryStream stream = new System.IO.MemoryStream(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, stream); doc.Open(); // Creamos el tipo de Font que vamos utilizar iTextSharp.text.Font _tituloFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Font _tituloFont2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font texto = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); // Escribimos el encabezamiento en el documento Paragraph paragraph1 = new Paragraph(@" DOCUMENTOS VENCIDOS", _tituloFont); paragraph1.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph1); Paragraph paragraph2 = new Paragraph(@" ", _tituloFont); paragraph2.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph2); //Creating iTextSharp Table from the DataTable data PdfPTable pdfTable = new PdfPTable(10); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; pdfTable.DefaultCell.BorderWidth = 1; //Adding Header row pdfTable.AddCell("Fecha"); pdfTable.AddCell("Fecha Venc."); pdfTable.AddCell("Cliente"); pdfTable.AddCell("Tipo Documento"); pdfTable.AddCell("Serie"); pdfTable.AddCell("Nro. Serie"); pdfTable.AddCell("Moneda"); pdfTable.AddCell("Monto Total"); pdfTable.AddCell("Monto Pagado"); pdfTable.AddCell("Saldo"); //Adding DataRow foreach (GridViewRow row in gridViewDocumentos.Rows) { Label lblFecha = row.FindControl("lblFecha") as Label; if (lblFecha != null) { pdfTable.AddCell(lblFecha.Text); } else { pdfTable.AddCell(""); } Label lblFechaVencimiento = row.FindControl("lblFechaVencimiento") as Label; if (lblFechaVencimiento != null) { pdfTable.AddCell(lblFechaVencimiento.Text); } else { pdfTable.AddCell(""); } Label lblCliente = row.FindControl("lblCliente") as Label; if (lblCliente != null) { pdfTable.AddCell(lblCliente.Text); } else { pdfTable.AddCell(""); } Label lblTipoDocumento = row.FindControl("lblTipoDocumento") as Label; if (lblTipoDocumento != null) { pdfTable.AddCell(lblTipoDocumento.Text); } else { pdfTable.AddCell(""); } Label lblSerie = row.FindControl("lblSerie") as Label; if (lblSerie != null) { pdfTable.AddCell(lblSerie.Text); } else { pdfTable.AddCell(""); } Label lblNroSerie = row.FindControl("lblNroSerie") as Label; if (lblNroSerie != null) { pdfTable.AddCell(lblNroSerie.Text); } else { pdfTable.AddCell(""); } Label lblMoneda = row.FindControl("lblMoneda") as Label; if (lblMoneda != null) { pdfTable.AddCell(lblMoneda.Text); } else { pdfTable.AddCell(""); } Label lblMontoTotal = row.FindControl("lblMontoTotal") as Label; if (lblMontoTotal != null) { pdfTable.AddCell(lblMontoTotal.Text); } else { pdfTable.AddCell(""); } Label lblMontoPagado = row.FindControl("lblMontoPagado") as Label; if (lblMontoPagado != null) { pdfTable.AddCell(lblMontoPagado.Text); } else { pdfTable.AddCell(""); } Label lblSaldo = row.FindControl("lblSaldo") as Label; if (lblSaldo != null) { pdfTable.AddCell(lblSaldo.Text); } else { pdfTable.AddCell(""); } } doc.Add(pdfTable); doc.Close(); stream.Close(); byte[] Result = stream.ToArray(); Sistema.GetInstancia().PDFActual = Result; // Session["pdf"] = Result; gridViewDocumentos.AllowPaging = true; if (Sistema.GetInstancia().PDFActual != null) { Response.Redirect("VisorPDFReportes.aspx"); } }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 14f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBold = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); BaseFont baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); if (writer.PageNumber == 1) { //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //Row 2 Phrase phrase = new Phrase(); phrase.Add(new Chunk(recordHeader, language == "en-US" ? new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK) : new Font(baseFont, 10f, Font.NORMAL, BaseColor.BLACK))); phrase.Add(new Chunk(" " + startDate + " ", new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK))); phrase.Add(new Chunk(To, language == "en-US" ? new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK) : new Font(baseFont, 12f, Font.NORMAL, BaseColor.BLACK))); phrase.Add(new Chunk(" " + endDate, new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK))); PdfPCell pdfCell4 = new PdfPCell(phrase); pdfCell4.PaddingLeft = 70f; //Row 3 iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(logoPath); myImage.ScaleToFit(50f, 50f); PdfPCell pdfCell5 = new PdfPCell(new Phrase(RenewalHeader, language == "en-US" ? baseFontBig : new Font(baseFont, 14f, 1, BaseColor.BLACK))); pdfCell5.PaddingTop = 0f; pdfCell5.PaddingLeft = 70f; pdfCell5.Top = 0f; PdfPCell pdfCell6 = new PdfPCell(); pdfCell6.PaddingTop = 0f; pdfCell6.Top = 0f; PdfPCell pdfCell7 = new PdfPCell(myImage); pdfCell7.Top = 0f; pdfCell7.PaddingTop = 4f; pdfCell7.PaddingRight = 10f; //set the alignment of all three cells and set border to 0 pdfCell4.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell5.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell4.VerticalAlignment = Element.ALIGN_TOP; pdfCell5.VerticalAlignment = Element.ALIGN_TOP; pdfCell6.VerticalAlignment = Element.ALIGN_TOP; pdfCell7.VerticalAlignment = Element.ALIGN_TOP; pdfCell4.Colspan = 3; pdfCell4.Border = 0; pdfCell5.Border = 0; pdfCell6.Border = 0; pdfCell7.Border = 0; pdfTab.AddCell(pdfCell5); pdfTab.AddCell(pdfCell6); pdfTab.AddCell(pdfCell7); if (!string.IsNullOrEmpty(fullName)) { PdfPCell pdfCell8 = new PdfPCell(new Phrase(fullName, baseFontBold)); pdfCell8.PaddingLeft = 70f; pdfCell8.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell8.VerticalAlignment = Element.ALIGN_TOP; pdfCell8.Colspan = 3; pdfCell8.Border = 0; pdfTab.AddCell(pdfCell8); } else { PdfPCell pdfCell8 = new PdfPCell(new Phrase(EmailId, baseFontBold)); pdfCell8.PaddingLeft = 70f; pdfCell8.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell8.VerticalAlignment = Element.ALIGN_TOP; pdfCell8.Colspan = 3; pdfCell8.Border = 0; pdfTab.AddCell(pdfCell8); PdfPCell pdfCell9 = new PdfPCell(new Phrase(Message, language == "en-US" ? new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.ITALIC, BaseColor.BLACK) : new Font(baseFont, 10f, Font.ITALIC, BaseColor.BLACK))); pdfCell9.PaddingLeft = 70f; pdfCell9.PaddingBottom = 10f; pdfCell9.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell9.VerticalAlignment = Element.ALIGN_TOP; pdfCell9.Colspan = 3; pdfCell9.Border = 0; pdfTab.AddCell(pdfCell9); } pdfTab.AddCell(pdfCell4); pdfTab.TotalWidth = document.PageSize.Width; pdfTab.WidthPercentage = 100; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing if (!string.IsNullOrEmpty(fullName)) { pdfTab.WriteSelectedRows(0, -1, 0, document.PageSize.Height - 30, writer.DirectContent); } else { pdfTab.WriteSelectedRows(0, -1, 0, document.PageSize.Height, writer.DirectContent); } } else { } }
/// <summary> /// 生成页脚 /// </summary> /// <param name="writer"></param> /// <returns></returns> public virtual PdfPTable GenerateFooter(iTextSharp.text.pdf.PdfWriter writer) { return(null); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); //iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.f.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); //iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); string pdfpath = HttpContext.Current.Server.MapPath(".") + "/images/logo_tagline.png"; Image image = iTextSharp.text.Image.GetInstance(pdfpath); // Phrase p1Header = new Phrase("PURCHASED ORDER"); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(image); PdfPCell pdfCell3 = new PdfPCell(); PdfPCell pdfCell4 = new PdfPCell(); PdfPCell pdfCell5 = new PdfPCell(); PdfPCell pdfCell6 = new PdfPCell(); string pdfpathfoot = HttpContext.Current.Server.MapPath(".") + "/images/GSTchallan.png"; Image imagefoot = iTextSharp.text.Image.GetInstance(pdfpathfoot); //Row 3 //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_TOP; pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell1.HorizontalAlignment = Element.ALIGN_TOP; pdfCell2.VerticalAlignment = Element.ALIGN_LEFT; pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.VerticalAlignment = Element.ALIGN_CENTER; pdfCell5.VerticalAlignment = Element.ALIGN_CENTER; pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell2.Colspan = 3; // pdfCell5.Colspan = 3; pdfCell2.Border = 0; pdfCell3.Border = 0; pdfCell4.Border = 0; pdfCell5.Border = 0; pdfCell6.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.AddCell(pdfCell4); pdfTab.AddCell(pdfCell5); pdfTab.AddCell(pdfCell6); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //PdfPTable table = new PdfPTable(3); //PdfPCell cell0 = new PdfPCell(image); //cell0.Colspan = 3; //cell0.HorizontalAlignment = Element.ALIGN_CENTER; //table.AddCell(cell0); //table.AddCell(""); //PdfPCell cell = new PdfPCell(new Phrase("Centillion Solutions and Services Pvt Ltd.\n iliyas")); //cell.Colspan = 3; //cell.HorizontalAlignment = Element.ALIGN_CENTER; //table.AddCell(cell); //table.AddCell(""); //PdfPCell cell1 = new PdfPCell(new Phrase("CIN:U72400KA2006PTC039877")); //cell1.Colspan = 3; //cell1.HorizontalAlignment = Element.ALIGN_CENTER; //table.AddCell(cell1); //table.AddCell("Row 2, Col 1"); //table.AddCell("Row 2, Col 1"); //table.AddCell("Row 3, Col 1"); //cell = new PdfPCell(new Phrase("Row 3, Col 2 and Col3")); //cell.Colspan = 2; //table.AddCell(cell); //cell = new PdfPCell(new Phrase("Row 4, Col 1 and Col2")); //cell.Colspan = 2; //table.AddCell(cell); //table.AddCell("Row 4, Col 3"); PdfPTable pdfTabfooter = new PdfPTable(2); //Row 1 PdfPCell pdfCellfoot1 = new PdfPCell(imagefoot); PdfPCell pdfCellfoot2 = new PdfPCell(); pdfCellfoot1.Border = 0; pdfCellfoot2.Border = 0; pdfCellfoot1.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellfoot2.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellfoot1.VerticalAlignment = Element.ALIGN_CENTER; pdfCellfoot2.VerticalAlignment = Element.ALIGN_CENTER; pdfCellfoot1.Colspan = 3; pdfTabfooter.AddCell(pdfCellfoot1); var a = document.PageSize.Bottom; pdfTabfooter.TotalWidth = document.PageSize.Width; //pdfTabfooter.WidthPercentage = 70; pdfTabfooter.WriteSelectedRows(0, -1, 0, document.PageSize.GetBottom(120), writer.DirectContent); //footer.writeSelectedRows(0, -1, 36, 64, writer.DirectContent); //set pdfContent value //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(40, document.PageSize.Height - 100); //cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(40, document.PageSize.GetBottom(70)); //cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); }
protected void btnExportPdf_Click(object sender, EventArgs e) { gridViewDocumentos.AllowPaging = false; BindData(); Document doc = new Document(PageSize.LETTER); doc.AddTitle("Estado de Cuenta"); doc.AddCreator("E&E Integra"); System.IO.MemoryStream stream = new System.IO.MemoryStream(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, stream); doc.Open(); // Creamos el tipo de Font que vamos utilizar iTextSharp.text.Font _tituloFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Font _tituloFont2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font texto = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font _cellFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); // Escribimos el encabezamiento en el documento Paragraph paragraph1 = new Paragraph(@"PORCENTAJES POR CLIENTES - VENDEDOR: " + ddlVendedores.SelectedItem.Text, _tituloFont); paragraph1.Alignment = Element.ALIGN_CENTER; doc.Add(paragraph1); Paragraph paragraph2 = new Paragraph(@" ", _tituloFont); paragraph2.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph2); //Creating iTextSharp Table from the DataTable data PdfPTable pdfTable = new PdfPTable(4); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; pdfTable.DefaultCell.BorderWidth = 1; //Adding Header row pdfTable.AddCell("Nombre"); pdfTable.AddCell("Nro Documento"); pdfTable.AddCell("Total acumulado"); pdfTable.AddCell("% sobre Total"); //Adding DataRow foreach (GridViewRow row in gridViewDocumentos.Rows) { Label lblNombre = row.FindControl("lblNombre") as Label; if (lblNombre != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblNombre.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblDetalle = row.FindControl("lblDetalle") as Label; if (lblDetalle != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblDetalle.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblTotal = row.FindControl("lblTotal") as Label; if (lblTotal != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblTotal.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblPorcentaje = row.FindControl("lblPorcentaje") as Label; if (lblPorcentaje != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblPorcentaje.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } } doc.Add(pdfTable); doc.Close(); stream.Close(); byte[] Result = stream.ToArray(); Sistema.GetInstancia().PDFActual = Result; // Session["pdf"] = Result; gridViewDocumentos.AllowPaging = true; if (Sistema.GetInstancia().PDFActual != null) { Response.Redirect("VisorPDFReportes.aspx"); } }
protected void btnExportPdf_Click(object sender, EventArgs e) { gridViewDocumentos.AllowPaging = false; BindData(); Document doc = new Document(PageSize.LETTER); doc.AddTitle("Estado de Cuenta"); doc.AddCreator("E&E Integra"); System.IO.MemoryStream stream = new System.IO.MemoryStream(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, stream); doc.Open(); // Creamos el tipo de Font que vamos utilizar iTextSharp.text.Font _tituloFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Font _tituloFont2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font texto = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font _cellFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); // Escribimos el encabezamiento en el documento Paragraph paragraph1 = new Paragraph(@"LISTADO CLIENTES - PRODUCTOS", _tituloFont); paragraph1.Alignment = Element.ALIGN_CENTER; doc.Add(paragraph1); Paragraph paragraph10 = new Paragraph(@"CLIENTE: " + ddlCliente.SelectedItem, _tituloFont); paragraph10.Alignment = Element.ALIGN_CENTER; doc.Add(paragraph10); Paragraph paragraph11 = new Paragraph(@"DESDE: " + txtFechaDesde.Text + " - HASTA: " + txtFechaHasta.Text, _tituloFont); paragraph11.Alignment = Element.ALIGN_CENTER; doc.Add(paragraph11); Paragraph paragraph2 = new Paragraph(@" ", _tituloFont); paragraph2.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph2); //Creating iTextSharp Table from the DataTable data PdfPTable pdfTable = new PdfPTable(6); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; pdfTable.DefaultCell.BorderWidth = 1; //Adding Header row pdfTable.AddCell("Cliente"); pdfTable.AddCell("Documento"); pdfTable.AddCell("Producto"); pdfTable.AddCell("Cantidad"); pdfTable.AddCell("Kilos"); pdfTable.AddCell("Total"); //Adding DataRow foreach (GridViewRow row in gridViewDocumentos.Rows) { Label lblCliente = row.FindControl("lblCliente") as Label; if (lblCliente != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblCliente.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblRUT = row.FindControl("lblRUT") as Label; if (lblRUT != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblRUT.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblProducto = row.FindControl("lblProducto") as Label; if (lblProducto != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblProducto.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblCantidad = row.FindControl("lblCantidad") as Label; if (lblCantidad != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblCantidad.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblKilos = row.FindControl("lblKilos") as Label; if (lblKilos != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblKilos.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } Label lblTotal = row.FindControl("lblTotal") as Label; if (lblTotal != null) { pdfTable.AddCell(new PdfPCell(new Phrase(lblTotal.Text, _cellFont))); } else { pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont))); } } doc.Add(pdfTable); doc.Close(); stream.Close(); byte[] Result = stream.ToArray(); Sistema.GetInstancia().PDFActual = Result; // Session["pdf"] = Result; gridViewDocumentos.AllowPaging = true; if (Sistema.GetInstancia().PDFActual != null) { Response.Redirect("VisorPDFReportes.aspx"); } }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontNormal1 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE); iTextSharp.text.Font baseFontNormal2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLUE); iTextSharp.text.Font baseFontNormal3 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLUE); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); PdfPCell p1Header = new PdfPCell(new Phrase("Hoang Tam", baseFontNormal1)) { Border = 0 }; PdfPCell p2Header = new PdfPCell(new Phrase("C14B Street No.9, Le Minh Xuan Industrial Park, Tan Nhut Ward, Binh Chanh District,\nHo Chi Minh City, Viet Nam", baseFontNormal2)) { Border = 0 }; PdfPCell p3Header = new PdfPCell(new Phrase("Tel: +84 (0) 28 3835 2741", baseFontNormal3)) { Border = 0 }; ////Table //PdfPTable table = new PdfPTable(2); //table.WidthPercentage = 100; ////0=Left, 1=Centre, 2=Right //table.HorizontalAlignment = 0; //table.SpacingBefore = 20f; //table.SpacingAfter = 30f; ////Cell no 1 //PdfPCell cell = new PdfPCell(); //cell.Border = 0; Image image = Image.GetInstance(path); image.ScaleAbsolute(90, 70); //cell.AddElement(image); //table.AddCell(cell); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(2); PdfPTable pdfTab1 = new PdfPTable(1); pdfTab1.AddCell(p1Header); pdfTab1.AddCell(p2Header); pdfTab1.AddCell(p3Header); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(pdfTab1, new PdfPCell() { Border = 0, PaddingRight = 20 //BackgroundColor = BaseColor.BLUE }); PdfPCell pdfCell2 = new PdfPCell(image); //PdfPCell pdfCell3 = new PdfPCell(image); String text = "Page " + writer.PageNumber + " of "; //Add paging to header { //cb.BeginText(); //cb.SetFontAndSize(bf, 12); //cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45)); //cb.ShowText(text); //cb.EndText(); //float len = bf.GetWidthPoint(text, 12); ////Adds "12" in Page 1 of 12 //cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45)); } //Add paging to footer { cb.BeginText(); cb.SetFontAndSize(bf, 12); cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30)); } //Row 2 PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal)); //Row 3 PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig)); PdfPCell pdfCell6 = new PdfPCell(); PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig)); //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell2.HorizontalAlignment = Element.ALIGN_RIGHT; //pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell1.VerticalAlignment = Element.ALIGN_TOP; pdfCell2.VerticalAlignment = Element.ALIGN_TOP; //pdfCell3.VerticalAlignment = Element.ALIGN_TOP; pdfCell4.VerticalAlignment = Element.ALIGN_TOP; pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.Colspan = 3; pdfCell1.Border = 0; pdfCell2.Border = 0; //pdfCell3.Border = 0; pdfCell4.Border = 0; pdfCell5.Border = 0; pdfCell6.Border = 0; pdfCell7.Border = 0; //pdfCell4.BorderWidthLeft = 1f; //pdfCell5.BorderWidthLeft = 1f; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); //pdfTab.AddCell(pdfCell3); //pdfTab.AddCell(pdfCell4); //pdfTab.AddCell(pdfCell5); //pdfTab.AddCell(pdfCell6); //pdfTab.AddCell(pdfCell7); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //set pdfContent value //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(40, document.PageSize.Height - 120); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 120); cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); //Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 //PdfPCell pdfCell1 = new PdfPCell(); //PdfPCell pdfCell2 = new PdfPCell(p1Header); //PdfPCell pdfCell3 = new PdfPCell(); String text = "Strona: " + writer.PageNumber + " z "; //Add paging to header /*{ * cb.BeginText(); * cb.SetFontAndSize(bf, 12); * cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45)); * cb.ShowText(text); * cb.EndText(); * float len = bf.GetWidthPoint(text, 12); * //Adds "12" in Page 1 of 12 * cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45)); * }*/ //Add paging to footer { cb.BeginText(); cb.SetFontAndSize(bf, 12); cb.SetTextMatrix(document.PageSize.GetRight(1) / 2 - text.Length /*document.PageSize.GetRight(350)*/, document.PageSize.GetBottom(30)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(1) / 2 + len - text.Length /*document.PageSize.GetRight(350) + len*/, document.PageSize.GetBottom(30)); } /* * //Row 2 * PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal)); * * //Row 3 * PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig)); * PdfPCell pdfCell6 = new PdfPCell(); * PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig)); * * //set the alignment of all three cells and set border to 0 * pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER; * pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; * pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER; * pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; * pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER; * pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; * pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER; * * pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM; * pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE; * pdfCell4.VerticalAlignment = Element.ALIGN_TOP; * pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE; * pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE; * pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE; * * pdfCell4.Colspan = 3; * * pdfCell1.Border = 0; * pdfCell2.Border = 0; * pdfCell3.Border = 0; * pdfCell4.Border = 0; * pdfCell5.Border = 0; * pdfCell6.Border = 0; * pdfCell7.Border = 0; * * //add all three cells into PdfTable * pdfTab.AddCell(pdfCell1); * pdfTab.AddCell(pdfCell2); * pdfTab.AddCell(pdfCell3); * pdfTab.AddCell(pdfCell4); * pdfTab.AddCell(pdfCell5); * pdfTab.AddCell(pdfCell6); * pdfTab.AddCell(pdfCell7); */ //pdfTab.TotalWidth = document.PageSize.Width - 80f; //pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing //pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //set pdfContent value //Move the pointer and draw line to separate header section from rest of page //cb.MoveTo(40, document.PageSize.Height - 100); //cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); //cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); }
private void saveFile_OKClick(object sender, EventArgs e) { switch (saveFile.Filter == "Файл PDF|*.PDF") { case (true): using (MemoryStream memory = new MemoryStream()) { pdffile.Document document = new pdffile.Document(pdffile.PageSize.A4.Rotate()); pdf.BaseFont baseFont = pdf.BaseFont.CreateFont(@"C:\arial.ttf", pdf.BaseFont.IDENTITY_H, pdf.BaseFont.NOT_EMBEDDED); pdffile.Font font = new pdffile.Font(baseFont, pdffile.Font.DEFAULTSIZE, pdffile.Font.NORMAL); pdf.PdfWriter pdfWriter = pdf.PdfWriter.GetInstance(document, memory); document.Open(); document.Add(new pdffile.Paragraph(Program.RedactTB.Text, font)); document.Close(); byte[] content = memory.ToArray(); using (FileStream stream = File.Create(saveFile.FileName)) { stream.Write(content, 0, (int)content.Length); } } break; case (false): if (saveFile.FileName != "") { switch (saveFile.FilterIndex) { case (1): StreamWriter writer = new StreamWriter(saveFile.FileName); writer.Write(Program.RedactTB.Text); writer.Close(); break; case (2): word.Application MSOW97 = new word.Application(); word.Document document97 = MSOW97.Documents.Add(Visible: true); word.Paragraph paragraph97 = document97.Paragraphs.Add(); paragraph97.Range.Text = textBox.Text; paragraph97.Range.Font.Name = Program.Font_Name; paragraph97.Range.Font.Size = Program.Font_Size; document97.SaveAs2(saveFile.FileName, word.WdSaveFormat.wdFormatDocument97); document97.Close(); MSOW97.Quit(); break; case (3): word.Application MSOW = new word.Application(); word.Document document = MSOW.Documents.Add(Visible: true); word.Paragraph paragraph = document.Paragraphs.Add(); paragraph.Range.Text = textBox.Text; paragraph.Range.Font.Name = Program.Font_Name; paragraph.Range.Font.Size = Program.Font_Size; document.SaveAs2(saveFile.FileName, word.WdSaveFormat.wdFormatDocumentDefault); document.Close(); MSOW.Quit(); break; } } break; } }
public void FacturaPDF() { FileStream fs = new FileStream("C:\\Users\\bryan\\Desktop\\ReportesFacturas\\Factura.pdf", FileMode.Create); Document document = new Document(iTextSharp.text.PageSize.LEGAL, 0, 0, 0, 0); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs); document.Open(); PdfPTable Tabla = new PdfPTable(4); document.Add(new Paragraph("\n")); // Creamos la imagen y le ajustamos el tamaño iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance("C:\\Users\\bryan\\source\\repos\\DesarrolloWeb_PP\\CapaPresentacion\\Images\\FondoFactura.png"); imagen.BorderWidth = 0; imagen.Alignment = Element.ALIGN_CENTER; float percentage = 0.0f; percentage = 488 / imagen.Width; imagen.ScalePercent(percentage * 100); // Insertamos la imagen en el documento document.Add(imagen); document.Add(new Paragraph("\n")); objDevolucion.c_idFactura = Convert.ToInt32(txt_idFactura.Text); Paragraph Factura = new Paragraph("Factura No. " + objDevolucion.MostrarEncabezado().Rows[0][0].ToString()); Factura.Alignment = Element.ALIGN_CENTER; document.Add(Factura); Paragraph Direccion = new Paragraph("Dirección: " + objDevolucion.MostrarEncabezado().Rows[0][1].ToString()); Direccion.Alignment = Element.ALIGN_CENTER; document.Add(Direccion); Paragraph NIT = new Paragraph("NIT: " + objDevolucion.MostrarEncabezado().Rows[0][2].ToString()); NIT.Alignment = Element.ALIGN_CENTER; document.Add(NIT); Paragraph Cliente = new Paragraph("Cliente: " + objDevolucion.MostrarEncabezado().Rows[0][3].ToString()); Cliente.Alignment = Element.ALIGN_CENTER; document.Add(Cliente); Paragraph Cajero = new Paragraph("Cajero: " + objDevolucion.MostrarEncabezado().Rows[0][4].ToString()); Cajero.Alignment = Element.ALIGN_CENTER; document.Add(Cajero); Paragraph TipoPago = new Paragraph("Tipo de Pago: " + objDevolucion.MostrarEncabezado().Rows[0][5].ToString()); TipoPago.Alignment = Element.ALIGN_CENTER; document.Add(TipoPago); Paragraph Fecha = new Paragraph("Fecha: " + objDevolucion.MostrarEncabezado().Rows[0][6].ToString()); Fecha.Alignment = Element.ALIGN_CENTER; document.Add(Fecha); Paragraph Hora = new Paragraph("Hora: " + objDevolucion.MostrarEncabezado().Rows[0][7].ToString()); Hora.Alignment = Element.ALIGN_CENTER; document.Add(Hora); document.Add(new Paragraph("\n")); Tabla.AddCell(new Paragraph("Producto")); Tabla.AddCell(new Paragraph("Precio")); Tabla.AddCell(new Paragraph("Cantidad")); Tabla.AddCell(new Paragraph("Subtotal")); foreach (DataRow row in objDevolucion.MostrarDetalleFacturaPDF().Rows) { Tabla.AddCell(new Paragraph(row[0].ToString())); Tabla.AddCell(new Paragraph(row[1].ToString())); Tabla.AddCell(new Paragraph(row[2].ToString())); Tabla.AddCell(new Paragraph(row[3].ToString())); } PdfPCell pcell = (new PdfPCell(new Phrase("Total: " + objDevolucion.MostrarEncabezado().Rows[0][8].ToString())) { Colspan = 4 }); pcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; Tabla.AddCell(pcell); document.Add(Tabla); document.Add(new Paragraph("\n")); Paragraph Gracias = new Paragraph("¡GRACIAS POR SU COMPRA!"); Gracias.Alignment = Element.ALIGN_CENTER; document.Add(Gracias); document.Close(); }
public override void OnStartPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { //Stream st = new Stream(); var headerTable = new PdfPTable(3); headerTable.SpacingBefore = 0; var cnt = data[0].GetType().GetProperties().Count(); var pdfHTable = new PdfPTable(cnt); headerTable.HorizontalAlignment = Element.ALIGN_CENTER; //byte[] data21 = File.ReadAllBytes(); //MemoryStream ms = new MemoryStream(data21); //iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Content/images/EPGM-LOGO.png")); //logo.SetAbsolutePosition(120, document.PageSize.Height - 90); //logo.ScalePercent(7f); //PdfPCell logoCell = new PdfPCell(); //logoCell.AddElement(logo); //logoCell.Border = 0; //logoCell.Colspan = 2; //logoCell.HorizontalAlignment = Element.ALIGN_CENTER; PdfPCell emptycel = new PdfPCell(); emptycel.Border = 0; headerTable.AddCell(emptycel); //headerTable.AddCell("hai"); //headerTable.AddCell("cell"); //headerTable.AddCell(" "); var count = data[0].GetType().GetProperties().Count(); List <object> headtext = new List <object>(); headtext.Add(fileName); //if ((disname != "")) // headtext.Add(disname); //headtext.Add("Report Generated for the Period of: " + fromdate + " To " + todate); var pdfheadertb = new PdfPTable(1); //headerTable.AddCell(logoCell); //headerTable.AddCell(" "); var celldat2 = new PdfPCell(new Phrase(12, "Growth Monitoring System", baseFontHeading)); celldat2.HorizontalAlignment = Element.ALIGN_CENTER; celldat2.Border = 0; pdfheadertb.AddCell(celldat2); var celldat = new PdfPCell(new Phrase(14, "Government of Telangana", baseFontHeading1)); celldat.HorizontalAlignment = Element.ALIGN_CENTER; celldat.Border = 0; pdfheadertb.AddCell(celldat); foreach (object colhead in headtext) { var celldata = new PdfPCell(new Phrase(12, colhead.ToString(), baseFontBold)); celldata.HorizontalAlignment = Element.ALIGN_CENTER; celldata.Border = 0; PdfPCell[] coldata = new PdfPCell[] { celldata }; PdfPRow rowdata = new PdfPRow(coldata); pdfheadertb.Rows.Add(rowdata); } pdfheadertb.HorizontalAlignment = Element.ALIGN_CENTER; var celldat1 = new PdfPCell(new Phrase(12, "Report Generated Time:" + System.DateTime.Now.Day + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year + " " + System.DateTime.Now.Hour + ":" + System.DateTime.Now.Minute, baseFontBig)); celldat1.HorizontalAlignment = Element.ALIGN_LEFT; celldat1.Border = 0; //document.Add(logo); var myType = data[0].GetType(); IList <PropertyInfo> properties = new List <PropertyInfo>(myType.GetProperties()); List <PdfPCell> cells = new List <PdfPCell>(); foreach (PropertyInfo prop in properties) { string propValue = prop.Name; //.Humanize(LetterCasing.Title); var cell = new PdfPCell(new Phrase(12, propValue, baseFontBold)); cells.Add(cell); } PdfPRow row = new PdfPRow(cells.ToArray <PdfPCell>()); pdfHTable.Rows.Add(row); PdfPTable reporttb = new PdfPTable(9); var col1 = new PdfPCell(new Phrase(12, " ", baseFontBig)); col1.Colspan = 5; col1.Border = 0; celldat1.Colspan = 4; reporttb.AddCell(col1); reporttb.AddCell(celldat1); if (document.PageNumber == 1) { document.Add(headerTable); document.Add(pdfheadertb); document.Add(reporttb); } document.Add(pdfHTable); PdfPTable footerTable = new PdfPTable(1); //byte[] data12 = File.ReadAllBytes(); //MemoryStream ms1 = new MemoryStream(data12); //iTextSharp.text.Image logo1 = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Content/images/EPGM-LOGO.png")); //logo1.SetAbsolutePosition(10, 100); //logo1.ScalePercent(40f); //PdfPCell addressCell = new PdfPCell(); //addressCell.HorizontalAlignment = Element.ALIGN_LEFT; //addressCell.AddElement(logo1); //addressCell.Border = 0; //footerTable.AddCell(addressCell); footerTable.TotalWidth = document.PageSize.Width - 80f; footerTable.WidthPercentage = 100; footerTable.WriteSelectedRows(0, -1, 40, document.PageSize.GetBottom(500), writer.DirectContent); }
public ActionResult DocuXmlPDF(int idCab) { try { var Org_XML = _db.Documento.FirstOrDefault(z => z.id_cab == idCab).xml_dte.ToString(); var html = helper.XmlFo4Pdf(Org_XML.Replace("xmlns=\"http://www.sii.cl/SiiDte\" ", "").Replace("\r\n", "")); XmlDocument doc = new XmlDocument(); doc.LoadXml(Org_XML); var Ted = doc.GetElementsByTagName("TED")[0].OuterXml; MemoryStream ms = new MemoryStream(); // Convierto el HTML en PDF ConverterProperties properties = new ConverterProperties(); properties.SetBaseUri("http://gs.pso.cl/Master/DocuXml?idCab=4923"); HtmlConverter.ConvertToPdf(html, ms, properties); // Genero el PDF417 MemoryStream msIMG = new MemoryStream(); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(ms.ToArray()); PdfStamper stamper = new PdfStamper(reader, msIMG); int n = reader.NumberOfPages; var msIMG2 = GenerateBarCodeZXing(Ted); //Inserto la imagen del PDF417 iTextSharp.text.Image QR = iTextSharp.text.Image.GetInstance(msIMG2, ImageFormat.Png); QR.SetAbsolutePosition(10, 200); stamper.GetOverContent(1).AddImage(QR); stamper.FormFlattening = false; //msIMG.Flush(); // Don't know if this is necessary //msIMG.Position = 0; //msIMG.Close(); //iTextSharp.text.pdf.PdfReader reader2 = new iTextSharp.text.pdf.PdfReader(msIMG.ToArray()); MemoryStream msMargen = new MemoryStream(); //WriterProperties writerProperties = new WriterProperties(); Document doc2 = new Document(iTextSharp.text.PageSize.LETTER, 200, 0, 100, 0); iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc2, msMargen); doc2.Open(); pdfWriter.Open(); PdfContentByte cb = pdfWriter.DirectContent; var page = pdfWriter.GetImportedPage(reader, 1); cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); //pdfWriter.SetMargins(0, 0, 0, 0); //pdfWriter.Close(); //ms.Close(); //msIMG.Close(); doc2.Close(); stamper.Close(); reader.Close(); return(File(msIMG.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf)); } catch (Exception) { return(null); } }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); PdfPTable tabCabecera = new PdfPTable(1); PdfPTable tabPie = new PdfPTable(1); PdfPCell celLineaCabecera = new PdfPCell(); PdfPCell celLegal = new PdfPCell(); PdfPCell celEmail = new PdfPCell(); PdfPCell celLineaPie = new PdfPCell(); //CABECERA iTextSharp.text.Image imagen2 = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/images/logo_kellogg.png")); celLineaCabecera.Image = imagen2; celLineaCabecera.BackgroundColor = new BaseColor(181, 25, 70); celLineaCabecera.Border = 0; celLineaCabecera.Padding = 3; celLineaCabecera.FixedHeight = 30f; celLineaCabecera.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; tabCabecera.AddCell(celLineaCabecera); tabCabecera.TotalWidth = document.PageSize.Width; tabCabecera.WriteSelectedRows(0, -1, 0, document.PageSize.Top, writer.DirectContent); //FOOTER //if (cf != null) //{ // if (cf.legal_x == true) // { celLegal.AddElement(new Paragraph(cf.legal, FontFactory.GetFont(FontFactory.HELVETICA, 8))); celLegal.PaddingLeft = 30; celLegal.PaddingRight = 30; celLegal.Border = 0; tabPie.AddCell(celLegal); } // else // { celLegal.AddElement(new Paragraph("", FontFactory.GetFont(FontFactory.HELVETICA, 8))); celLegal.Border = 0; tabPie.AddCell(celLegal); } // if (cf.mail_x == true) // { celEmail.AddElement(new Paragraph(cf.mail, FontFactory.GetFont(FontFactory.HELVETICA, 8))); celEmail.PaddingLeft = 30; celEmail.PaddingRight = 30; celEmail.Border = 0; tabPie.AddCell(celEmail); } // else // { celEmail.AddElement(new Paragraph("", FontFactory.GetFont(FontFactory.HELVETICA, 8))); celEmail.Border = 0; tabPie.AddCell(celEmail); } // celLineaPie.AddElement(new Chunk("")); // celLineaPie.BackgroundColor = new BaseColor(181, 25, 70); // celLineaPie.Border = 0; // celLineaPie.FixedHeight = 30f; // tabPie.AddCell(celLineaPie); // tabPie.TotalWidth = document.PageSize.Width; // tabPie.WriteSelectedRows(0, -1, 0, document.PageSize.GetBottom(tabPie.TotalHeight), writer.DirectContent); //} // //else if (cv != null) { if (cv.legal_x == true) { celLegal.AddElement(new Paragraph(cv.legal, FontFactory.GetFont(FontFactory.HELVETICA, 8))); celLegal.PaddingLeft = 30; celLegal.PaddingRight = 30; celLegal.Border = 0; tabPie.AddCell(celLegal); } else { celLegal.AddElement(new Paragraph("", FontFactory.GetFont(FontFactory.HELVETICA, 8))); celLegal.Border = 0; tabPie.AddCell(celLegal); } if (cv.mail_x == true) { celEmail.AddElement(new Paragraph(cv.mail, FontFactory.GetFont(FontFactory.HELVETICA, 8))); celEmail.PaddingLeft = 30; celEmail.PaddingRight = 30; celEmail.Border = 0; tabPie.AddCell(celEmail); } else { celEmail.AddElement(new Paragraph("", FontFactory.GetFont(FontFactory.HELVETICA, 8))); celEmail.Border = 0; tabPie.AddCell(celEmail); } celLineaPie.AddElement(new Chunk("")); celLineaPie.BackgroundColor = new BaseColor(181, 25, 70); celLineaPie.Border = 0; celLineaPie.FixedHeight = 30f; tabPie.AddCell(celLineaPie); tabPie.TotalWidth = document.PageSize.Width; tabPie.WriteSelectedRows(0, -1, 0, document.PageSize.GetBottom(tabPie.TotalHeight), writer.DirectContent); } }
public void ReporteVentasPDF() { FileStream fs = new FileStream("C:\\Users\\bryan\\Desktop\\ReportesFacturas\\ReporteVentas.pdf", FileMode.Create); Document document = new Document(iTextSharp.text.PageSize.LEGAL.Rotate(), 0, 0, 0, 0); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs); document.Open(); PdfPTable Tabla = new PdfPTable(10); document.Add(new Paragraph("\n")); // Creamos la imagen y le ajustamos el tamaño iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance("C:\\Users\\bryan\\source\\repos\\DesarrolloWeb_PP\\CapaPresentacion\\Images\\FondoFactura.png"); imagen.BorderWidth = 0; imagen.Alignment = Element.ALIGN_CENTER; float percentage = 0.0f; percentage = 795 / imagen.Width; imagen.ScalePercent(percentage * 100); // Insertamos la imagen en el documento document.Add(imagen); document.Add(new Paragraph("\n")); Paragraph Encabezado = new Paragraph("REPORTE DE VENTAS " + txtFechaInicio.Text + " AL " + txtFechaFinal.Text); Encabezado.Alignment = Element.ALIGN_CENTER; document.Add(Encabezado); document.Add(new Paragraph("\n")); Tabla.AddCell(new Paragraph("Cajero")); Tabla.AddCell(new Paragraph("NIT Cliente")); Tabla.AddCell(new Paragraph("Cliente")); Tabla.AddCell(new Paragraph("Fecha Venta")); Tabla.AddCell(new Paragraph("Hora Venta")); Tabla.AddCell(new Paragraph("Tipo Pago")); Tabla.AddCell(new Paragraph("Producto")); Tabla.AddCell(new Paragraph("Precio")); Tabla.AddCell(new Paragraph("Cantidad")); Tabla.AddCell(new Paragraph("Subtotal")); objReportes.c_FechaInicio = txtFechaInicio.Text; objReportes.c_FechaFinal = txtFechaFinal.Text; foreach (DataRow row in objReportes.ReporteVentas().Rows) { Tabla.AddCell(new Paragraph(row[0].ToString())); Tabla.AddCell(new Paragraph(row[1].ToString())); Tabla.AddCell(new Paragraph(row[2].ToString())); Tabla.AddCell(new Paragraph(row[3].ToString())); Tabla.AddCell(new Paragraph(row[4].ToString())); Tabla.AddCell(new Paragraph(row[5].ToString())); Tabla.AddCell(new Paragraph(row[6].ToString())); Tabla.AddCell(new Paragraph(row[7].ToString())); Tabla.AddCell(new Paragraph(row[8].ToString())); Tabla.AddCell(new Paragraph(row[9].ToString())); } PdfPCell pcell = (new PdfPCell(new Phrase("TOTAL INGRESOS = " + objReportes.GananciasTotales().Rows[0][0].ToString())) { Colspan = 10 }); pcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; Tabla.AddCell(pcell); document.Add(Tabla); document.Add(new Paragraph("\n")); Paragraph Gracias = new Paragraph("- FIN DEL REPORTE -"); Gracias.Alignment = Element.ALIGN_CENTER; document.Add(Gracias); document.Close(); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); Phrase p1Header = new Phrase(NombreDoc, verdana); #region LOGOTIPO string fileName = "LOGODESCOELECTRIC.jpg"; FileInfo f = new FileInfo(fileName); string fullname = f.FullName; // FileInfo direccion = new FileInfo(@"C:\Documents and Settings\User\My Documents\Dropbox\DESCO\COTIZAR LUIGI"); // string imageFilePath = @"C:\logoDesco/DESCO log.GIF"; string imageFilePath = @"C:\logoDesco/LOGODESCOELECTRIC.jpg"; iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath); jpg.ScaleToFit(80f, 80f); // jpg.IsNestable(); jpg.SetAbsolutePosition(0, 0); //LOGOTIPO // jpg.SpacingBefore = 30f; // jpg.SpacingAfter = 1f; // jpg.Alignment = Element.ALIGN_LEFT; // FileInfo direccion2 = new FileInfo("LOG2.PNG"); // string imageFilePath2 = direccion2.DirectoryName + "/LOG2.PNG"; /* * string imageFilePath2 = @"C:\logoDesco/LOG2.PNG"; * iTextSharp.text.Image jpg2 = iTextSharp.text.Image.GetInstance(imageFilePath2); * jpg2.ScaleToFit(115f, 115f); * // jpg.IsNestable(); * jpg2.SetAbsolutePosition(0, 0); */ #endregion LOGOTIPO String text2 = "Blvd. Federico Benítez 401-B La mesa, Tijuana B.C. C.P.22105 Tel/Fax: 6262712 http//:www.descoelectric.com"; String text = "Page " + writer.PageNumber + " of "; #region Numeracion de pagina y Fijacion de LOGOTIPO //Add paging to header { headerTemplate.AddImage(jpg); // headerTemplate.AddImage(jpg2); cb.AddTemplate(headerTemplate, 50, 842 - 125); /* cb.BeginText(); * cb.SetFontAndSize(bf, 12); * cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45)); * cb.ShowText(text); * cb.EndText(); * float len = bf.GetWidthPoint(text, 12); * //Adds "12" in Page 1 of 12 * cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45)); */ } //Agregar la direccion al Footer { cb.BeginText(); cb.SetFontAndSize(bf, 8); cb.SetTextMatrix(document.PageSize.GetRight(480), document.PageSize.GetBottom(10)); cb.ShowText(text2); cb.EndText(); // float len = bf.GetWidthPoint(text, 10); // cb.AddTemplate(footerTemplate2, document.PageSize.GetRight(700), document.PageSize.GetBottom(25)); } //Add paging to footer { cb.BeginText(); cb.SetFontAndSize(bf, 8); cb.SetTextMatrix(document.PageSize.GetRight(330), document.PageSize.GetBottom(25)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 8); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(330) + len, document.PageSize.GetBottom(25)); } #endregion Numeracion de pagina y Fijacion de LOGOTIPO #region Tabla Titulo y Numero de Cotizacion //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(p1Header); //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.VerticalAlignment = Element.ALIGN_TOP; pdfCell1.Border = 0; pdfCell2.Border = 0; //TABLA ANIDADA DE NUMERO DE COTIZACION Y FECHA PdfPTable table = new PdfPTable(1); table.TotalWidth = 124f; table.LockedWidth = true; table.HorizontalAlignment = 2; PdfPTable nestedTable = new PdfPTable(1); table.WidthPercentage = 100; PdfPCell header = new PdfPCell(new Phrase(8, "No. " + NoDoc, arial2)); header.HorizontalAlignment = 1; // header.BackgroundColor = BaseColor.LIGHT_GRAY; iTextSharp.text.Image imagen1 = iTextSharp.text.Image.GetInstance(libBarCode.Barcode.GetImagenCodigo(CodigoDoc, 1, 20, false), BaseColor.GRAY); imagen1.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; // imagen1.ScalePercent(10); PdfPCell cellx = new PdfPCell(imagen1, true); cellx.HorizontalAlignment = 1; // cellx.Border = 0; // cellx.AddElement(new Chunk(imagen1,5,-5)); // nestedTable.AddCell(cellx); /* * PdfPCell header2 = new PdfPCell(new Phrase(8,CodigoDoc, arial2)); * header2.HorizontalAlignment = 1; * header2.Border = 0; * nestedTable.AddCell(header2); */ PdfPCell header3 = new PdfPCell(new Phrase(8, "Fecha: " + FechaDoc.Day + "/" + FechaDoc.Month + "/" + FechaDoc.Year, arial2)); header3.HorizontalAlignment = 1; // header2.BackgroundColor = BaseColor.LIGHT_GRAY; /* * PdfPCell header4 = new PdfPCell(new Phrase(8, "Factura: " + NoFactura, arial2)); * header4.HorizontalAlignment = 1; * // header3.BackgroundColor = BaseColor.LIGHT_GRAY; * * PdfPCell header5 = new PdfPCell(new Phrase(8, "Remision: " + NoRemision, arial2)); * header5.HorizontalAlignment = 1; * * PdfPCell header6 = new PdfPCell(new Phrase(8, "Cotizacion: " + NoCotizacion, arial)); * header6.HorizontalAlignment = 1; */ //TITULO,NUMERO Y FECHA table.AddCell(header); // table.AddCell(header4); table.AddCell(cellx); table.AddCell(header3); // table.AddCell(header5); // table.AddCell(header6); PdfPCell anidado = new PdfPCell(table); anidado.HorizontalAlignment = 2; anidado.Border = 0; //TITULO,NUMERO Y FECHA //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(anidado); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 50, writer.DirectContent); #endregion Tabla Titulo y Numero de Cotizacion #region Tabla Nombre del PROVEEDOR PdfPTable tablaCte = new PdfPTable(2); tablaCte.TotalWidth = document.PageSize.Width - 95f; tablaCte.LockedWidth = true; tablaCte.WidthPercentage = 70; float[] widths = new float[] { 1f, 3f }; tablaCte.SetWidths(widths); tablaCte.SpacingAfter = 10; PdfPCell cte = new PdfPCell(new Phrase("PROVEEDOR:" + "\n TOTAL EN DOLAR: " + _total.ToString("#,##0.00"), arial)); cte.Border = 0; cte.VerticalAlignment = Element.ALIGN_CENTER; tablaCte.AddCell(cte); PdfPCell cte2 = new PdfPCell(new Phrase(NombreProveedor, arial)); cte2.Border = 0; cte2.VerticalAlignment = Element.ALIGN_CENTER; tablaCte.AddCell(cte2); /* PdfPCell b = new PdfPCell(); * b.Border = 0; * b.Colspan = 2; * // cte.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(b); * * PdfPCell cto = new PdfPCell(new Phrase("CONTACTO:", arial)); * cto.Border = 0; * cto.VerticalAlignment = Element.ALIGN_MIDDLE; * tablaCte.AddCell(cto); * * PdfPCell cto2 = new PdfPCell(new Phrase(NombreContacto, arial2)); * cto2.Border = 0; * cto2.VerticalAlignment = Element.ALIGN_MIDDLE; * tablaCte.AddCell(cto2); * * PdfPCell proyecto = new PdfPCell(new Phrase("VENDEDOR:", arial)); * proyecto.Border = 0; * proyecto.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(proyecto); * * PdfPCell proyecto2 = new PdfPCell(new Phrase(NombreVendedor, arial2)); * proyecto2.Border = 0; * proyecto2.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(proyecto2); * * * PdfPCell lugar = new PdfPCell(new Phrase("LUGAR DE ENTREGA: TIJUANA B.C.", ITextEvents.arial)); * lugar.Border = 0; * lugar.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(lugar); */ tablaCte.WriteSelectedRows(0, -1, 50, document.PageSize.Height - 110, writer.DirectContent); #endregion Tabla Nombre del PROVEEDOR #region Titulos de Columnas PdfPTable NombreColumnas = new PdfPTable(5); NombreColumnas.TotalWidth = document.PageSize.Width - 90f; NombreColumnas.LockedWidth = true; NombreColumnas.WidthPercentage = 70; float[] widths2 = new float[] { 1f, 4f, 8f, 1f, 2f }; NombreColumnas.SetWidths(widths2); PdfPCell item = new PdfPCell(new Phrase("ITEM", arial2)); item.HorizontalAlignment = 1; item.VerticalAlignment = Element.ALIGN_MIDDLE; item.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(item); PdfPCell Catalogo = new PdfPCell(new Phrase("CATALOGO", arial2)); Catalogo.HorizontalAlignment = 1; Catalogo.VerticalAlignment = Element.ALIGN_MIDDLE; Catalogo.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(Catalogo); PdfPCell Descrip = new PdfPCell(new Phrase("DESCRIPCION", arial2)); Descrip.HorizontalAlignment = 1; Descrip.VerticalAlignment = Element.ALIGN_MIDDLE; Descrip.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(Descrip); PdfPCell Cantidad = new PdfPCell(new Phrase("CANT.", arial2)); Cantidad.HorizontalAlignment = 1; Cantidad.VerticalAlignment = Element.ALIGN_MIDDLE; Cantidad.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(Cantidad); PdfPCell FacturaP = new PdfPCell(new Phrase("FACTURA", arial2)); FacturaP.HorizontalAlignment = 1; FacturaP.VerticalAlignment = Element.ALIGN_MIDDLE; FacturaP.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(FacturaP); NombreColumnas.WriteSelectedRows(0, -1, 51, document.PageSize.Height - 170, writer.DirectContent); #endregion Titulos de Columnas //set pdfContent value //Move the pointer and draw line to separate header section from rest of page /* cb.MoveTo(40, document.PageSize.Height - 100); * cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); * cb.Stroke(); * * //Move the pointer and draw line to separate footer section from rest of page * cb.MoveTo(40, document.PageSize.GetBottom(50)); * cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); * cb.Stroke(); */ }
public void ToPDF(iTextSharp.text.pdf.PdfWriter w) { PdfContentByte cb = w.DirectContent; cb.SetLineWidth((float)Settings.Thickness); if (Settings.Fill != null) { cb.SetColorFill(Settings.Fill.ToPDFColor()); } if (Settings.Stroke != null) { cb.SetColorStroke(Settings.Stroke.ToPDFColor()); } if (Geometry.GetType() == typeof(Dyn.Arc)) { Dyn.Arc arc = Geometry as Dyn.Arc; cb.MoveTo(arc.StartPoint.X, arc.EndPoint.Y); cb.CurveTo(arc.PointAtParameter(0.5).X, arc.PointAtParameter(0.5).Y, arc.EndPoint.X, arc.EndPoint.Y); } else if (Geometry.GetType() == typeof(Dyn.Line)) { Dyn.Line line = Geometry as Dyn.Line; cb.MoveTo(line.StartPoint.X, line.StartPoint.Y); cb.LineTo(line.EndPoint.X, line.EndPoint.Y); } else if (Geometry.GetType() == typeof(Dyn.Circle)) { Dyn.Circle circle = Geometry as Dyn.Circle; cb.Circle(circle.CenterPoint.X, circle.CenterPoint.Y, circle.Radius); } else if (Geometry.GetType() == typeof(Dyn.Ellipse)) { Dyn.Ellipse ellipse = Geometry as Dyn.Ellipse; cb.Ellipse(ellipse.StartPoint.X, ellipse.StartPoint.Y, ellipse.EndPoint.X, ellipse.EndPoint.Y); } else if (Geometry.GetType() == typeof(Dyn.Rectangle)) { Dyn.Rectangle rect = Geometry as Dyn.Rectangle; cb.Rectangle(rect.Center().X, rect.Center().Y, rect.Width, rect.Height); } else if (Geometry.GetType() == typeof(Dyn.Polygon)) { Dyn.Polygon p = Geometry as Dyn.Polygon; foreach (var curve in p.Curves()) { CurveToPDF(curve, cb); } } else if (Geometry.GetType() == typeof(Dyn.PolyCurve)) { Dyn.PolyCurve pc = Geometry as Dyn.PolyCurve; foreach (var curve in pc.Curves()) { CurveToPDF(curve, cb); } } else if (Geometry.GetType() == typeof(Dyn.NurbsCurve)) { Dyn.NurbsCurve nc = Geometry as Dyn.NurbsCurve; foreach (var linearc in nc.ApproximateWithArcAndLineSegments()) { CurveToPDF(linearc, cb); } } else if (Geometry.GetType() == typeof(Dyn.Curve)) { Dyn.Curve curve = Geometry as Dyn.Curve; CurveToPDF(curve, cb); } else { throw new Exception(Properties.Resources.NotSupported); } if (Settings.Fill != null && Settings.Stroke != null) { cb.FillStroke(); } else { if (Settings.Stroke != null) { cb.Stroke(); } if (Settings.Fill != null) { cb.Fill(); } } }
private void GenerarPDF(decimal importe, string nroRecibo, string Observaciones) { try { Document doc = new Document(PageSize.LETTER); // Indicamos donde vamos a guardar el documento System.IO.MemoryStream ms = new System.IO.MemoryStream(); //PdfWriter writer = PdfWriter.GetInstance(doc,new FileStream(@"C:\recibo.pdf", FileMode.Create)); doc.AddTitle("Recibo Pago"); doc.AddCreator("E&E Integra"); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms); doc.Open(); // Creamos el tipo de Font que vamos utilizar iTextSharp.text.Font _tituloFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Font _tituloFont2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font _cuotaFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font texto = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); string imageURL = Server.MapPath("~//Imagenes") + "\\logo.png"; iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL); jpg.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_LEFT; jpg.ScaleAbsolute(177f, 100f); doc.Add(jpg); // Escribimos el encabezamiento en el documento Paragraph paragraph1 = new Paragraph(@" RUT: " + Session["rut"].ToString(), _tituloFont); paragraph1.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph1); Paragraph paragraph2 = new Paragraph(@" Recibo Oficial", _tituloFont); paragraph2.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph2); Paragraph paragraph3 = new Paragraph(@" Nro. Recibo: " + nroRecibo.ToString(), _tituloFont2); paragraph3.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph3); Paragraph paragraph4 = new Paragraph(@" Moneda: " + ddlMoneda.SelectedValue, _tituloFont2); paragraph4.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph4); Paragraph paragraph5 = new Paragraph(@" Importe " + importe, _tituloFont); paragraph5.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph5); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); String nom = ddlClientes.SelectedItem.Text; Paragraph paragraph6 = new Paragraph(@"Recibimos de " + nom + " la cantidad de " + importe + " por concepto de pago de deuda"); paragraph6.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph6); doc.Add(Chunk.NEWLINE); Paragraph paragraph7 = new Paragraph(@"Observaciones:", _tituloFont); paragraph7.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph7); String resultString = Regex.Replace(Observaciones, @"^\s+$[\r\n]*", "", RegexOptions.Multiline); Paragraph paragraph8 = new Paragraph(@resultString, _cuotaFont); paragraph8.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph8); doc.Add(Chunk.NEWLINE); Paragraph paragraph9 = new Paragraph(@"Paysandú, " + DateTime.Now.Day + " de " + MonthName(DateTime.Now.Month) + " de " + DateTime.Now.Year); paragraph9.Alignment = Element.ALIGN_RIGHT; doc.Add(paragraph9); float antes = writer.GetVerticalPosition(true); float diff = antes - 353; for (int i = 0; i < diff / 20; i++) { doc.Add(Chunk.NEWLINE); } doc.Add(jpg); doc.Add(paragraph1); doc.Add(paragraph2); doc.Add(paragraph3); doc.Add(paragraph4); doc.Add(paragraph5); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(paragraph6); doc.Add(Chunk.NEWLINE); doc.Add(paragraph7); doc.Add(paragraph8); doc.Add(Chunk.NEWLINE); doc.Add(paragraph9); doc.Close(); byte[] Result = ms.ToArray(); writer.Close(); Sistema.GetInstancia().PDFActual = Result; //Sistema.GetInstancia().AumentarNroRecibo(Session["rut"].ToString()); // Session["pdf"] = Result; if (Sistema.GetInstancia().PDFActual != null) { //Response.Redirect("VisorPDF.aspx"); Response.Write("<script>"); Response.Write("window.open('CobroDeudores.aspx', '_blank');"); Response.Write("window.location.href = 'VisorPDF.aspx';"); Response.Write("</script>"); } } catch { } }
/*Evento que ocurre antes de pasar a una nueva página en el documento. Se utiliza para insertar el pie de página.*/ public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); string pathWater = string.Empty; string nota_pie = string.Empty; float anchoWater = 0; float heightWater = 0; PdfPCell cell = null; PdfPRow row = null; Image img = null; float escalaW = 0; string pathAcreimg = string.Empty; float escalaH = 0; float escalaAcreW = 0; float escalaAcreH = 0; string subcontrata = string.Empty; string url_informe = string.Empty; int pageN = writer.PageNumber; Rectangle nroTotal = document.PageSize; var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11); iTextSharp.text.Font normal = FontFactory.GetFont(FontFactory.HELVETICA, 6); iTextSharp.text.Font bold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8); JArray data = JArray.Parse(parametro); Paragraph p; if (lmr) { //listcells = new List<PdfPCell>(); pathImg = data[0]["logo"].ToString(); escalaW = (float)data[0]["escalaWidthLogo"]; escalaH = (float)data[0]["escalaHeightLogo"]; pathWater = data[0]["logoWater"].ToString(); anchoWater = (float)data[0]["escalaWidthLogoWater"]; heightWater = (float)data[0]["escalaHeightLogoWater"]; subTitulo = data[0]["titulo_lmr"].ToString(); footer_txt = data[0]["footer"].ToString(); WriteWaterMark(document, pathWater, anchoWater, heightWater); float[] head = { 98, 325, 100 }; PdfPTable tblTableTitulo = new PdfPTable(head.Length); tblTableTitulo.TotalWidth = document.PageSize.Width; tblTableTitulo.WidthPercentage = 100; tblTableTitulo.SetWidths(head); tblTableTitulo.DefaultCell.Border = Rectangle.NO_BORDER; //creo la imagen de bureau cell = new PdfPCell(new Paragraph("")); img = Image.GetInstance(urlBase + pathImg); img.ScaleAbsolute(escalaW, escalaH); cell.AddElement(img); cell.Border = 0; tblTableTitulo.AddCell(cell); //creo el titulo cell = new PdfPCell(new Paragraph(new Chunk(titulo, boldFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_TOP; cell.PaddingTop = 13; cell.Border = 0; tblTableTitulo.AddCell(cell); tblTableTitulo.CompleteRow(); //listcells = new List<PdfPCell>(); cell = new PdfPCell(new Phrase("")); cell.Border = 0; tblTableTitulo.AddCell(cell); cell = new PdfPCell(new Paragraph(new Chunk(subTitulo))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.Top = 100; cell.VerticalAlignment = Element.ALIGN_MIDDLE; cell.Border = 0; tblTableTitulo.AddCell(cell); tblTableTitulo.CompleteRow(); tblTableTitulo.WriteSelectedRows(0, -1, 20, writer.PageSize.GetTop(document.TopMargin) + 140, writer.DirectContent); //número de páginas String str = "Página " + pageN.ToString() + " / "; cb.SetRGBColorFill(100, 100, 100); cb.BeginText(); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 8); //agrega el rotulo //cb.SetTextMatrix(document.PageSize.Width - document.RightMargin - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.SetTextMatrix(document.PageSize.Width - 50 - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.ShowText(str); cb.EndText(); //agrega el total de paginas //cb.AddTemplate(template, document.PageSize.Width - document.RightMargin - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); cb.AddTemplate(template, document.PageSize.Width - 50 - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); float[] cabecera = { 350, 78 }; PdfPTable pdfTab = new PdfPTable(cabecera.Length); pdfTab.TotalWidth = document.PageSize.Width; pdfTab.WidthPercentage = 100; pdfTab.SetWidths(cabecera); pdfTab.DefaultCell.Border = Rectangle.NO_BORDER; Chunk footer = new Chunk(footer_txt, bold); Chunk Subfooter = new Chunk("Information based on: https://globalmrl.com" + "\nThe results of this analysis refer only to the materials subjected to the analysis.\n" + "This analysis result can not be reproduced in whole or in part without the express authorization of Inspectorate Services Perú S.A.C.\n" + "There is no responsibility on the part of Inspectorate Services Perú S.A.C. in relation to the Data Review provided\n", normal); //byte[] b = IronBarCode.QRCodeWriter.CreateQrCode("https://app.bureauveritas.com.pe/agrifood_test/", 50, IronBarCode.QRCodeWriter.QrErrorCorrectionLevel.Medium).ToPngBinaryData(); //Image imgs = Image.GetInstance(b); //List<PdfPCell> listCells = new List<PdfPCell>(); cell = new PdfPCell(new Paragraph(Subfooter)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); cell = new PdfPCell(new Paragraph("")); cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); pdfTab.CompleteRow(); cell = new PdfPCell(new Paragraph(footer)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); //imagen de codigo de barras cell = new PdfPCell(new Paragraph("")); cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); pdfTab.CompleteRow(); pdfTab.WriteSelectedRows(0, -1, 50, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); } if (arfd) { //listcells = new List<PdfPCell>(); pathImg = data[0]["logo"].ToString(); escalaW = (float)data[0]["escalaWidthLogo"]; escalaH = (float)data[0]["escalaHeightLogo"]; pathWater = data[0]["logoWater"].ToString(); anchoWater = (float)data[0]["escalaWidthLogoWater"]; heightWater = (float)data[0]["escalaHeightLogoWater"]; subTitulo = data[0]["titulo_arfd"].ToString(); footer_txt = data[0]["footer"].ToString(); WriteWaterMark(document, pathWater, anchoWater, heightWater); float[] head = { 98, 325, 100 }; PdfPTable tblTableTitulo = new PdfPTable(head.Length); tblTableTitulo.TotalWidth = document.PageSize.Width; tblTableTitulo.WidthPercentage = 100; tblTableTitulo.SetWidths(head); tblTableTitulo.DefaultCell.Border = Rectangle.NO_BORDER; //creo la imagen de bureau cell = new PdfPCell(new Paragraph("")); img = Image.GetInstance(urlBase + pathImg); img.ScaleAbsolute(escalaW, escalaH); cell.AddElement(img); cell.Border = 0; tblTableTitulo.AddCell(cell); //creo el titulo cell = new PdfPCell(new Paragraph(new Chunk(titulo, boldFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_TOP; cell.PaddingTop = 13; cell.Border = 0; tblTableTitulo.AddCell(cell); tblTableTitulo.CompleteRow(); //listcells = new List<PdfPCell>(); cell = new PdfPCell(new Phrase("")); cell.Border = 0; tblTableTitulo.AddCell(cell); cell = new PdfPCell(new Paragraph(new Chunk(subTitulo))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.Top = 100; cell.VerticalAlignment = Element.ALIGN_MIDDLE; cell.Border = 0; tblTableTitulo.AddCell(cell); tblTableTitulo.CompleteRow(); tblTableTitulo.WriteSelectedRows(0, -1, 20, writer.PageSize.GetTop(document.TopMargin) + 140, writer.DirectContent); //número de páginas String str = "Página " + pageN.ToString() + " / "; cb.SetRGBColorFill(100, 100, 100); cb.BeginText(); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 8); //agrega el rotulo //cb.SetTextMatrix(document.PageSize.Width - document.RightMargin - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.SetTextMatrix(document.PageSize.Width - 50 - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.ShowText(str); cb.EndText(); //agrega el total de paginas //cb.AddTemplate(template, document.PageSize.Width - document.RightMargin - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); cb.AddTemplate(template, document.PageSize.Width - 50 - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); float[] cabecera = { 350, 78 }; PdfPTable pdfTab = new PdfPTable(cabecera.Length); pdfTab.TotalWidth = document.PageSize.Width; pdfTab.WidthPercentage = 100; pdfTab.SetWidths(cabecera); pdfTab.DefaultCell.Border = Rectangle.NO_BORDER; Chunk footer = new Chunk(footer_txt, bold); //Chunk footer = new Chunk("Av. Elmer Faucett N° 444. distrito del Callao, Provincia Constitucional del Callao - Perú\n Central: (511) 613 - 8080 / www.bureauveritas.com", bold); Chunk Subfooter = new Chunk("Los resultados presentados corresponden sólo a la muestra indicada." + "\nLos resultados de este análisis se refieren únicamente a las materias sometidas al análisis.\n" + "Este resultado de análisis no puede ser reproducido total o parcialmente sin la autorización expresa de Inspectorate Service Perú S.A.C\n" + "No existe ninguna responsabilidad por parte de Inspectorate Service Perú S.A.C\n" + "en relación proporcionada respecto a los valores cuantificados inferiores al LC.", normal); //byte[] b = IronBarCode.QRCodeWriter.CreateQrCode("https://app.bureauveritas.com.pe/agrifood_test/", 50, IronBarCode.QRCodeWriter.QrErrorCorrectionLevel.Medium).ToPngBinaryData(); //Image imgs = Image.GetInstance(b); //List<PdfPCell> listCells = new List<PdfPCell>(); cell = new PdfPCell(new Paragraph(Subfooter)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); cell = new PdfPCell(new Paragraph("")); cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); //PdfPRow row = new Pd pdfTab.CompleteRow(); cell = new PdfPCell(new Paragraph(footer)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); //imagen de codigo de barras cell = new PdfPCell(new Paragraph("")); cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); pdfTab.CompleteRow(); //pdfTab.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); pdfTab.WriteSelectedRows(0, -1, 50, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); } if (traza) { //listcells = new List<PdfPCell>(); pathImg = data[0]["logo"].ToString(); escalaW = (float)data[0]["escalaWidthLogo"]; escalaH = (float)data[0]["escalaHeightLogo"]; pathWater = data[0]["logoWater"].ToString(); anchoWater = (float)data[0]["escalaWidthLogoWater"]; heightWater = (float)data[0]["escalaHeightLogoWater"]; subTitulo = data[0]["titulo_traza"].ToString(); footer_txt = data[0]["footer"].ToString(); WriteWaterMark(document, pathWater, anchoWater, heightWater); float[] head = { 98, 325, 100 }; PdfPTable tblTableTitulo = new PdfPTable(head.Length); tblTableTitulo.TotalWidth = document.PageSize.Width; tblTableTitulo.WidthPercentage = 100; tblTableTitulo.SetWidths(head); tblTableTitulo.DefaultCell.Border = Rectangle.NO_BORDER; //creo la imagen de bureau cell = new PdfPCell(new Paragraph("")); img = Image.GetInstance(urlBase + pathImg); img.ScaleAbsolute(escalaW, escalaH); cell.AddElement(img); cell.Border = 0; tblTableTitulo.AddCell(cell); //listcells.Add(cell); //creo el titulo cell = new PdfPCell(new Paragraph(new Chunk(titulo, boldFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_TOP; cell.PaddingTop = 13; cell.Border = 0; tblTableTitulo.AddCell(cell); tblTableTitulo.CompleteRow(); //listcells = new List<PdfPCell>(); cell = new PdfPCell(new Phrase("")); cell.Border = 0; tblTableTitulo.AddCell(cell); cell = new PdfPCell(new Paragraph(new Chunk(subTitulo))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.Top = 100; cell.VerticalAlignment = Element.ALIGN_MIDDLE; cell.Border = 0; tblTableTitulo.AddCell(cell); tblTableTitulo.CompleteRow(); tblTableTitulo.WriteSelectedRows(0, -1, 20, writer.PageSize.GetTop(document.TopMargin) + 140, writer.DirectContent); //número de páginas String str = "Página " + pageN.ToString() + " / "; cb.SetRGBColorFill(100, 100, 100); cb.BeginText(); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 8); //agrega el rotulo //cb.SetTextMatrix(document.PageSize.Width - document.RightMargin - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.SetTextMatrix(document.PageSize.Width - 50 - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.ShowText(str); cb.EndText(); //agrega el total de paginas //cb.AddTemplate(template, document.PageSize.Width - document.RightMargin - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); cb.AddTemplate(template, document.PageSize.Width - 50 - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); float[] cabecera = { 350, 78 }; PdfPTable pdfTab = new PdfPTable(cabecera.Length); pdfTab.TotalWidth = document.PageSize.Width; pdfTab.WidthPercentage = 100; pdfTab.SetWidths(cabecera); pdfTab.DefaultCell.Border = Rectangle.NO_BORDER; Chunk footer = new Chunk(footer_txt, bold); Chunk Subfooter = new Chunk("Los resultados presentados corresponden sólo a la muestra indicada." + "\nLos resultados de este análisis se refieren únicamente a las materias sometidas al análisis.\n" + "Este resultado de análisis no puede ser reproducido total o parcialmente sin la autorización expresa de Inspectorate Service Perú S.A.C\n" + "No existe ninguna responsabilidad por parte de Inspectorate Service Perú S.A.C\n" + "en relación proporcionada respecto a los valores cuantificados inferiores al LC.", normal); //byte[] b = IronBarCode.QRCodeWriter.CreateQrCode("https://app.bureauveritas.com.pe/agrifood_test/", 50, IronBarCode.QRCodeWriter.QrErrorCorrectionLevel.Medium).ToPngBinaryData(); //Image imgs = Image.GetInstance(b); List <PdfPCell> listCells = new List <PdfPCell>(); cell = new PdfPCell(new Paragraph(Subfooter)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); cell = new PdfPCell(new Paragraph("")); cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); //PdfPRow row = new Pd pdfTab.CompleteRow(); cell = new PdfPCell(new Paragraph(footer)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); //imagen de codigo de barras cell = new PdfPCell(new Paragraph("")); cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 5; cell.Border = 0; pdfTab.AddCell(cell); pdfTab.CompleteRow(); //pdfTab.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); pdfTab.WriteSelectedRows(0, -1, 50, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); } if (informe) { Rectangle re = new Rectangle(0, 0, 13, document.GetTop(document.TopMargin) + 350); re.BackgroundColor = custom; try { PdfContentByte under = writer.DirectContentUnder; under.BeginText(); under.EndText(); under.Rectangle(re); under.Stroke(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } //número de páginas String str = "Página " + pageN.ToString() + " / "; //float len = this.RunDateFont.BaseFont.GetWidthPoint(text, this.RunDateFont.Size); cb.SetRGBColorFill(100, 100, 100); cb.BeginText(); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 8); //agrega el rotulo //cb.SetTextMatrix(document.PageSize.Width - document.RightMargin - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.SetTextMatrix(document.PageSize.Width - 50 - str.Length - template.Width, document.PageSize.GetTop(document.TopMargin) + 10); cb.ShowText(str); cb.EndText(); //agrega el total de paginas //cb.AddTemplate(template, document.PageSize.Width - document.RightMargin - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); cb.AddTemplate(template, document.PageSize.Width - 50 - str.Length - 10, document.PageSize.GetTop(document.TopMargin) + 10); //escribe cabecera float tot = document.LeftMargin + document.RightMargin; float[] head = { 50, 180, 100 }; PdfPTable tblTableTitulo = new PdfPTable(head.Length); tblTableTitulo.TotalWidth = document.PageSize.Width; tblTableTitulo.WidthPercentage = 100; tblTableTitulo.SetWidths(head); //seteo una lista de celdas //listcells = new List<PdfPCell>(); pathImg = data[0]["logo"].ToString(); escalaW = (float)data[0]["escalaWidthLogo"]; escalaH = (float)data[0]["escalaHeightLogo"]; pathWater = data[0]["logoWater"].ToString(); anchoWater = (float)data[0]["escalaWidthLogoWater"]; heightWater = (float)data[0]["escalaHeightLogoWater"]; footer_txt = data[0]["footer"].ToString(); subcontrata = data[0]["subcontrata"].ToString(); nota_pie = data[0]["notas_pie"].ToString(); url_informe = data[0]["url_informe"].ToString(); //agrego el sello de agua WriteWaterMark(document, pathWater, anchoWater, heightWater); if (data[0]["acreditacion"] != null) { foreach (JObject jObject in data[0]["acreditacion"].Children <JToken>()) { titulo = jObject["cabecera_informe"].ToString(); subTitulo = jObject["titulo_informe"].ToString(); } } else { titulo = data[0]["titulo_default"].ToString(); subTitulo = data[0]["subtitulo_default"].ToString(); } //Agrego el subtitulo writer.DirectContent.BeginText(); writer.DirectContent.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 12); writer.DirectContent.SetTextMatrix((document.PageSize.Width / 2) - subTitulo.Length - 13, document.PageSize.GetTop(document.TopMargin) + 30); writer.DirectContent.ShowTextAligned(PdfContentByte.ALIGN_CENTER, subTitulo, (document.PageSize.Width / 2), document.PageSize.GetTop(document.TopMargin) + 30, 0); writer.DirectContent.EndText(); //termino de agregar el subtitulo //creo la imagen de bureau cell = new PdfPCell(new Paragraph("")); img = Image.GetInstance(urlBase + pathImg); img.ScaleAbsolute(escalaW, escalaH); cell.AddElement(img); cell.Border = 0; tblTableTitulo.AddCell(cell); //listcells.Add(cell); if (subcontrata != "0") { titulo = ""; } //creo el titulo cell = new PdfPCell(new Paragraph(new Chunk(titulo, boldFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_TOP; cell.PaddingTop = 13; cell.Border = 0; tblTableTitulo.AddCell(cell); //listcells.Add(cell); //agrega acreditación cell = new PdfPCell(); if (subcontrata == "0") { if (data[0]["acreditacion"] != null) { foreach (JObject jObject in data[0]["acreditacion"].Children <JToken>()) { escalaAcreW = (float)jObject["escalaWidth"]; escalaAcreH = (float)jObject["escalaHeight"]; pathAcreimg = jObject["path_img"].ToString(); img = Image.GetInstance(urlBase + pathAcreimg); img.ScaleAbsolute(escalaAcreW, escalaAcreH); cell.AddElement(img); } } } cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_MIDDLE; cell.Border = 0; tblTableTitulo.AddCell(cell); //listcells.Add(cell); //seteo una nueva fila //row = new PdfPRow(listcells.ToArray()); //row.SetWidths(head); //tblTableTitulo.Rows.Add(row); //listcells = new List<PdfPCell>(); //cell = new PdfPCell(new Phrase("")); //cell.Border = 0; //listcells.Add(cell); //cell = new PdfPCell(new Paragraph(new Chunk(""))); //cell.HorizontalAlignment = Element.ALIGN_CENTER; //cell.Top = 100; //cell.VerticalAlignment = Element.ALIGN_MIDDLE; //cell.Border = 0; //listcells.Add(cell); //PdfPRow rows = new PdfPRow(listcells.ToArray()); //float[] vs = { 13, 500 }; //rows.SetWidths(vs); //tblTableTitulo.Rows.Add(rows); tblTableTitulo.CompleteRow(); tblTableTitulo.SetWidths(head); //tblTableTitulo.WriteSelectedRows(0, -1,document.PageSize.GetLeft(document.LeftMargin) - 30, writer.PageSize.GetTop(document.TopMargin) + 140, writer.DirectContent); tblTableTitulo.WriteSelectedRows(0, -1, 20, writer.PageSize.GetTop(document.TopMargin) + 140, writer.DirectContent); //PdfContentByte cbtest = writer.DirectContent; //PdfPTable table = new PdfPTable(1); //table.TotalWidth = 400f; //table.AddCell("Test"); //table.WriteSelectedRows(0, -1, 200, 50, cbtest); //Create PdfTable object float[] cabecera = { 220, 80 }; PdfPTable pdfTab = new PdfPTable(cabecera.Length); pdfTab.TotalWidth = document.PageSize.Width; pdfTab.WidthPercentage = 100; pdfTab.SetWidths(cabecera); pdfTab.DefaultCell.Border = Rectangle.NO_BORDER; Chunk footer = new Chunk(footer_txt.ToString(), bold); Chunk Subfooter = new Chunk(nota_pie, normal); //byte[] b = IronBarCode.QRCodeWriter.CreateQrCode("https://app.bureauveritas.com.pe/agrifood_test/", 50, IronBarCode.QRCodeWriter.QrErrorCorrectionLevel.Medium).ToPngBinaryData(); var qr = new BarcodeQRCode(url_informe, 1, 1, null); var img_qr = qr.GetImage(); img_qr.ScaleAbsolute(50, 50); //Image imgs = Image.GetInstance(b); //List<PdfPCell> listCells = new List<PdfPCell>(); cell = new PdfPCell(new Paragraph(Subfooter)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.Border = 0; cell.PaddingTop = 5; pdfTab.AddCell(cell); cell = new PdfPCell(); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.VerticalAlignment = Element.ALIGN_RIGHT; cell.AddElement(img_qr); cell.Rowspan = 2; cell.Border = 0; cell.PaddingTop = 5; pdfTab.AddCell(cell); cell = new PdfPCell(new Paragraph(footer)); cell.PaddingTop = 5; cell.VerticalAlignment = Element.ALIGN_CENTER; cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.Border = 0; pdfTab.AddCell(cell); //imagen de codigo de barras cell = new PdfPCell(); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.VerticalAlignment = Element.ALIGN_RIGHT; cell.Border = 0; cell.PaddingTop = 5; pdfTab.AddCell(cell); pdfTab.CompleteRow(); //pdfTab.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); pdfTab.WriteSelectedRows(0, -1, 50, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); } }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font (iTextSharp.text.Font.FontFamily.HELVETICA, 9f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); //iTextSharp.text.Font baseFontBig = // new iTextSharp.text.Font // (iTextSharp.text.Font.FontFamily.HELVETICA, 12f, // iTextSharp.text.Font.BOLD, // iTextSharp.text.BaseColor.BLACK); string datetime = DateTime.Now.ToString("dd-MM-yyyy"); datetime = datetime + " \n " + writer.PageNumber; Phrase p1Header = new Phrase(datetime, baseFontNormal); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(); PdfPCell pdfCell3 = new PdfPCell(p1Header); //Row 2 //String text = "Mukasurat " + writer.PageNumber; PdfPCell pdfCell4 = new PdfPCell(new Phrase("Mukasurat " + writer.PageNumber, baseFontNormal)); //Add paging to header { //cb.BeginText(); //cb.SetFontAndSize(bf, 12); //cb.SetTextMatrix(document.PageSize.GetRight(200), // document.PageSize.GetTop(25)); //cb.ShowText(text); //cb.EndText(); //float len = bf.GetWidthPoint(text, 12); ////Adds "12" in Page 1 of 12 //cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) // + len, document.PageSize.GetTop(25)); } //Add paging to footer { //cb.BeginText(); //cb.SetFontAndSize(bf, 12); //cb.SetTextMatrix(document.PageSize.GetRight(180), // document.PageSize.GetBottom(30)); //cb.ShowText(text); //cb.EndText(); //float len = bf.GetWidthPoint(text, 12); //cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30)); } //Row 3 //PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig)); //PdfPCell pdfCell6 = new PdfPCell(); //PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig)); //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCell4.HorizontalAlignment = Element.ALIGN_RIGHT; //pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER; //pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; //pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.VerticalAlignment = Element.ALIGN_TOP; pdfCell3.VerticalAlignment = Element.ALIGN_TOP; pdfCell4.VerticalAlignment = Element.ALIGN_TOP; //pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE; //pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE; //pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE; //pdfCell4.Colspan = 3; pdfCell1.Border = 0; pdfCell2.Border = 0; pdfCell3.Border = 0; //pdfCell4.Border = 0; //pdfCell5.Border = 0; //pdfCell6.Border = 0; //pdfCell7.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.AddCell(pdfCell4); //pdfTab.AddCell(pdfCell5); //pdfTab.AddCell(pdfCell6); //pdfTab.AddCell(pdfCell7); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 20, writer.DirectContent); //set pdfContent value //Move the pointer and draw line to separate header section from rest of page //cb.MoveTo(40, document.PageSize.Height - 100); //cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); //cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page //cb.MoveTo(40, document.PageSize.GetBottom(50)); //cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); //cb.Stroke(); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font time = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 11f, Font.NORMAL); Image logo = Image.GetInstance(HttpContext.Current.Server.MapPath("~/assets/images/SLEmpresarial.png")); logo.ScaleToFit(150f, 62f); Phrase p1Header = new Phrase("PROPUESTA TÉCNICO ECONÓMICA\n EXÁMENES MÉDICOS\n OCUPACIONALES", baseFontNormal); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); float[] width = { 100f, 320f, 100f }; pdfTab.SetWidths(width); pdfTab.TotalWidth = 520f; pdfTab.LockedWidth = true; //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(logo); PdfPCell pdfCell2 = new PdfPCell(p1Header); String text = "Página " + writer.PageNumber + " de "; //Add paging to header { cb.BeginText(); cb.SetFontAndSize(bf, 12); cb.SetTextMatrix(document.PageSize.GetRight(120), document.PageSize.GetTop(45)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); //Adds "12" in Page 1 of 12 cb.AddTemplate(headerTemplate, document.PageSize.GetRight(120) + len, document.PageSize.GetTop(45)); } //Add paging to footer { Image logoSoftware = Image.GetInstance(HttpContext.Current.Server.MapPath("~/assets/images/SLEmpresarial.png")); logoSoftware.ScaleToFit(140f, 50f); var leftCol = new Paragraph("Mukesh Salaria\n" + "Software Engineer", time); var rightCol = new Paragraph("saluslaboris.com.pe\n", time); var phone = new Paragraph("Teléfono: (511) 6407309", time); var address = new Paragraph(" ESTE DOCUMENTO ES PROPIEDAD\n" + " INTELECTUAL DE SALUS LABORIS", time); var fax = new Paragraph("Av. Alfredo Benavides 4994\n Surco", time); leftCol.Alignment = Element.ALIGN_LEFT; rightCol.Alignment = Element.ALIGN_RIGHT; fax.Alignment = Element.ALIGN_RIGHT; phone.Alignment = Element.ALIGN_LEFT; address.Alignment = Element.ALIGN_CENTER; var footerTbl = new PdfPTable(3) { TotalWidth = 520f, HorizontalAlignment = Element.ALIGN_CENTER, LockedWidth = true }; float[] widths = { 150f, 220f, 150f }; footerTbl.SetWidths(widths); var footerCell1 = new PdfPCell(logoSoftware); var footerCell2 = new PdfPCell(); var footerCell3 = new PdfPCell(rightCol); var sep = new PdfPCell(); var footerCell4 = new PdfPCell(phone); var footerCell5 = new PdfPCell(address); var footerCell6 = new PdfPCell(fax); footerCell1.Border = 0; footerCell2.Border = 0; footerCell3.Border = 0; footerCell4.Border = 0; footerCell5.Border = 0; footerCell6.Border = 0; footerCell6.HorizontalAlignment = Element.ALIGN_RIGHT; sep.Border = 0; sep.FixedHeight = 10f; footerCell3.HorizontalAlignment = Element.ALIGN_RIGHT; footerCell6.PaddingLeft = 0; sep.Colspan = 3; footerTbl.AddCell(footerCell1); footerTbl.AddCell(footerCell2); footerTbl.AddCell(footerCell3); footerTbl.AddCell(sep); footerTbl.AddCell(footerCell4); footerTbl.AddCell(footerCell5); footerTbl.AddCell(footerCell6); footerTbl.WriteSelectedRows(0, -1, 40, 80, writer.DirectContent); } PdfPCell pdfCell3 = new PdfPCell(); PdfPCell pdfCell4 = new PdfPCell(); PdfPCell pdfCell5 = new PdfPCell(new Phrase("")); //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCell5.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCell2.PaddingTop = 9f; pdfCell3.PaddingTop = 20f; pdfCell5.PaddingTop = 9f; pdfCell1.Border = 0; pdfCell2.Border = 0; pdfCell3.Border = 0; pdfCell4.Border = 0; pdfCell5.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.AddCell(pdfCell4); pdfTab.AddCell(pdfCell5); pdfTab.TotalWidth = 520f; pdfTab.LockedWidth = true; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(40, document.PageSize.Height - 100); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); }
protected void Button1_Click(object sender, EventArgs e) { /* Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); * PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test.pdf", FileMode.Create)); * doc.Open(); * Paragraph paragraph = new Paragraph("My first Line \n My Second Line "); * doc.Add(paragraph); * doc.Close();*/ Response.ContentType = "application/pdf"; Response.AppendHeader( "Content-Disposition", "attachment; filename=Constancia.pdf" ); using (Document document = new Document()) { pdfw = PdfWriter.GetInstance(document, Response.OutputStream); // document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); document.Open(); cb = pdfw.DirectContent; ////////////////////////////////////////////// iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance("C:/Users/Pepe/Desktop/Fundanet/Sistema Fundanet/Sistema Fundanet/CapaPresentacion/Imagenes/FundanetBannersuperior.png"); imagen.BorderWidth = 0; imagen.Alignment = Element.ALIGN_MIDDLE; float percentage = 0.0f; percentage = 150 / imagen.Width; imagen.ScalePercent(percentage * 350); document.Add(imagen); //////////////////////////////////////////////// /* * iTextSharp.text.Image imagen2 = iTextSharp.text.Image.GetInstance("C:/Users/Pepe/Desktop/Fundanet/Sistema Fundanet/Sistema Fundanet/CapaPresentacion/Imagenes/Prueba.png"); * imagen2.Alignment = iTextSharp.text.Image.UNDERLYING; * imagen.BorderWidth = 0; * imagen.Alignment = Element.ALIGN_MIDDLE; * float percentage2 = 0.0f; * percentage = 150 / imagen.Width; * imagen.ScalePercent(percentage2 * 2000); * document.Add(imagen2);*/ ///////////////////////////////////////////////////////////////////// fuente = FontFactory.GetFont(FontFactory.HELVETICA, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.BOLD).BaseFont; cb.SetFontAndSize(fuente, 16); cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); document.Add(new Paragraph(" \n \n \n \n")); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Recibo De Pago: ", 300, 700, 0); ////////////////////////////////////////////////////////////////////////////////////////// var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14); var phrase2 = new Phrase(); phrase2.Add(new Chunk("Se otorga a: \n \n")); phrase2.Add(new Chunk("Giuseppe Adamo \n \n", boldFont)); phrase2.Add(new Chunk("por haber pagado satisfactoriamente el curso \n \n ")); phrase2.Add(new Chunk("#### \n \n", boldFont)); phrase2.Add(new Chunk("realizado en la Ciudad de Caracas y culminado en la fecha \n \n")); phrase2.Add(new Chunk("####### \n \n", boldFont)); phrase2.Add(new Chunk("con fecha de la transaccion \n \n")); phrase2.Add(new Chunk("####### \n \n \n \n \n", boldFont)); Paragraph parrafo = new Paragraph(); parrafo.Alignment = Element.ALIGN_JUSTIFIED; parrafo.Add(phrase2); document.Add(parrafo); ////////////////////////////////////////////////////////////////////////////////////////// var boldFont2 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12); var phrase3 = new Phrase(); phrase3.Add(new Chunk("_________________________\n ", boldFont2)); phrase3.Add(new Chunk("Luis Molner \n ", boldFont2)); phrase3.Add(new Chunk("Director Academico \n ", boldFont2)); Paragraph parrafo2 = new Paragraph(); parrafo2.Alignment = Element.ALIGN_CENTER; parrafo2.Add(phrase3); document.Add(parrafo2); document.Close(); } }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); Font fonteNormal = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.BOLD); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 100; float[] larguras = new float[] { 2f, 0.5f, 7f }; pdfTab.SetWidths(larguras); PdfPCell celulaIcone; PdfPCell celulaTexto; PdfPCell celulaLogo; celulaLogo = new PdfPCell(); ImagemLogo.ScaleAbsolute(100, 50); celulaLogo.AddElement(ImagemLogo); celulaLogo.Border = 0; celulaLogo.Rowspan = 3; pdfTab.AddCell(celulaLogo); celulaIcone = new PdfPCell(); celulaIcone.Border = 0; ImagemEmail.ScaleAbsolute(12, 12); celulaIcone.AddElement(ImagemEmail); pdfTab.AddCell(celulaIcone); celulaTexto = new PdfPCell(new Phrase("*****@*****.**", fonteNormal)); celulaTexto.Border = 0; pdfTab.AddCell(celulaTexto); celulaIcone = new PdfPCell(); celulaIcone.Border = 0; ImagemWhats.ScaleAbsolute(12, 12); celulaIcone.AddElement(ImagemWhats); pdfTab.AddCell(celulaIcone); celulaTexto = new PdfPCell(new Phrase("(51) 00035-3739", fonteNormal)); celulaTexto.Border = 0; pdfTab.AddCell(celulaTexto); celulaIcone = new PdfPCell(); celulaIcone.Border = 0; ImagemMaps.ScaleAbsolute(12, 12); celulaIcone.AddElement(ImagemMaps); pdfTab.AddCell(celulaIcone); celulaTexto = new PdfPCell(new Phrase("Rua Hoefel Sander, 165, Fazenda São Borja - São Leopoldo - RS | CEP 93044-830", fonteNormal)); celulaTexto.Border = 0; pdfTab.AddCell(celulaTexto); //Add paging to footer { cb.BeginText(); cb.SetFontAndSize(bf, 10); cb.SetTextMatrix(document.PageSize.GetLeft(190), document.PageSize.GetBottom(30)); cb.ShowText("Entre Rodas Assistência Técnica Automotiva"); cb.EndText(); float len = bf.GetWidthPoint("text", 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(80) + len, document.PageSize.GetBottom(30)); } pdfTab.WriteSelectedRows(0, -1, 110, document.PageSize.Height - 10, writer.DirectContent); //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(40, document.PageSize.Height - 70); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 70); cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); Phrase p1Header = new Phrase(null, null); //removing Header HTML COntent if (HeaderText != null) { FontFactory.RegisterDirectories(); List <IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(HeaderText), null); for (int k = 0; k < htmlarraylist.Count; k++) { p1Header.Add((IElement)htmlarraylist[k]); } } Phrase p1Footer = new Phrase(null, null); //removing Footer HTML COntent if (FooterText != null) { FontFactory.RegisterDirectories(); List <IElement> htmlarrayFooterlist = HTMLWorker.ParseToList(new StringReader(FooterText), null); for (int m = 0; m < htmlarrayFooterlist.Count; m++) { p1Footer.Add((IElement)htmlarrayFooterlist[m]); } } //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); pdfTab.WidthPercentage = 90; float[] tblDescWidth52 = new float[3]; tblDescWidth52[0] = 25; tblDescWidth52[1] = 72; tblDescWidth52[2] = 2; pdfTab.SetWidths(tblDescWidth52); String text = "Page " + writer.PageNumber + " of "; //We will have to create separate cells to include image logo and 2 separate strings //Row 1 if (HeaderRequired) { PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(p1Header); PdfPCell pdfCell3 = new PdfPCell(); // iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/customer Images/ReportLogo/" + LogoPath)); // iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance("F:/MAIN V10/Sharda_Hospital/Sharda_12_08_2016/WinApps/ReportLogo/Win7645logo3.PNG"); // imgLogo.ScaleToFit(80, 60); // pdfCell1.AddElement(imgLogo); string base64Image = LogoPath; // new 18-08 Regex regex = new Regex(@"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)"); // new 18-08 Match match = regex.Match(base64Image); // new 18-08 Image image = Image.GetInstance( // new 18-08 Convert.FromBase64String(match.Groups["data"].Value) // new 18-08 ); image.ScaleToFit(80, 60); // new 18-08 pdfCell1.AddElement(image); // new 18-08 //Row 2 PdfPCell pdfCell4 = new PdfPCell(new Phrase(null, baseFontNormal)); //Row 3 //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.VerticalAlignment = Element.ALIGN_CENTER; pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.VerticalAlignment = Element.ALIGN_TOP; pdfCell4.Colspan = 3; pdfCell1.Border = 0; pdfCell2.Border = 0; pdfCell3.Border = 0; pdfCell4.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.AddCell(pdfCell4); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //Move the pointer and draw line to separate header section from rest of page if (BorderRequired) { cb.MoveTo(40, document.PageSize.Height - 100); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); cb.Stroke(); } } //footer code if (FooterRequired) { //Move the pointer and draw line to separate footer section from rest of page if (BorderRequired) { cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); } //Add Footer text to footer PdfPTable pdfTaba = new PdfPTable(1); PdfPCell pdfCellfooter = new PdfPCell(p1Footer); pdfCellfooter.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellfooter.Border = 0; pdfCellfooter.VerticalAlignment = Element.ALIGN_BOTTOM; if (PaperSize == "") { pdfTaba.TotalWidth = document.PageSize.Width - 80f; } else { pdfTaba.TotalWidth = document.PageSize.Width; } pdfTaba.WidthPercentage = 100; pdfTaba.AddCell(pdfCellfooter); //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing // pdfTaba.WriteSelectedRows(0, -1, document.PageSize.GetRight(550), document.PageSize.GetBottom(50), writer.DirectContent); if (PaperSize == "A4 Size") { pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 750, writer.DirectContent); } else { pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 500, writer.DirectContent); } } if (PageRequired) { //Add paging to footer cb.BeginText(); cb.SetFontAndSize(bf, 8); cb.SetTextMatrix(document.PageSize.GetRight(120), document.PageSize.GetBottom(35)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(120) + len, document.PageSize.GetBottom(35)); } if (BorderRequired) { //Add Paging to Border var content = writer.DirectContent; var pageBorderRect = new Rectangle(document.PageSize); pageBorderRect.Left += 40f; pageBorderRect.Right -= 40f; pageBorderRect.Top -= 30f; pageBorderRect.Bottom += 30f; content.SetColorStroke(BaseColor.BLACK); content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height); content.Stroke(); } }
public override void OnStartPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { document.SetMargins(15f, 15f, 15f, 15f); base.OnStartPage(writer, document); }
public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); int pageN = writer.PageNumber; string text = pageN + " - "; float len = baseFont.GetWidthPoint(text, 8); Rectangle pageSize = document.PageSize; pdfContent = writer.DirectContent; pdfContent.SetRGBColorFill(100, 100, 100); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, 8); pdfContent.SetTextMatrix(pageSize.Width / 2, pageSize.GetBottom(30)); pdfContent.ShowText(text); pdfContent.EndText(); pdfContent.AddTemplate(pageNumberTemplate, (pageSize.Width / 2) + len, pageSize.GetBottom(30)); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, 8); pdfContent.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, printTime.ToString(), pageSize.GetRight(40), pageSize.GetBottom(30), 0); pdfContent.EndText(); }
public override void OnStartPage(PdfWriter writer, iTextSharp.text.Document document) { iTextSharp.text.Image header = iTextSharp.text.Image.GetInstance(PathResolver.MapPath("images/ADB_Logo.gif")); PdfPTable tableHeader = new PdfPTable(2); tableHeader.WidthPercentage = 100; PdfPCell imageHeaderCell = new PdfPCell(header); imageHeaderCell.Rowspan = 2; imageHeaderCell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right imageHeaderCell.Border = 0; imageHeaderCell.PaddingBottom = 3; tableHeader.AddCell(imageHeaderCell); Font helvetica20 = FontFactory.GetFont(FontFactory.HELVETICA, 16); PdfPCell typeNameCell = new PdfPCell(new Phrase(TypesReader.GetDiagramName(this.type), helvetica20)); typeNameCell.HorizontalAlignment = 2; typeNameCell.Border = 0; tableHeader.AddCell(typeNameCell); PdfPCell adbCell = new PdfPCell(new Phrase(GlobalStringResource.ADB, helvetica20)); adbCell.HorizontalAlignment = 2; adbCell.Border = 0; tableHeader.AddCell(adbCell); PdfPCell lineCell = new PdfPCell(); lineCell.Colspan = 2; lineCell.Border = 1; lineCell.PaddingBottom = 5; tableHeader.AddCell(lineCell); document.Add(tableHeader); }