public void build() { try { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + ImageUrl); float x = image.Width; float y = image.Height; float retio = x / y; float pageHeight = Document.PageSize.Height; if (IsHeader) { //fit to screen x = Document.PageSize.Width; y = x / retio; marginBottom = (int)(pageHeight - y); } image.ScaleToFit(x, x / retio); image.SetAbsolutePosition(Left, Top); PdfContentByte cb = Writer.DirectContent; PdfTemplate tp = cb.CreateTemplate(x, x / retio); tp.AddImage(image); cb.AddTemplate(tp, 0, marginBottom); } catch (Exception e) { } }
public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); int pageN = writer.PageNumber; //String text = "Page " + pageN + "/"; //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(); iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Path.Combine(Environment.CurrentDirectory, "img", "footer.png")); float w = document.PageSize.Width; float h = 80; logo.Alignment = Element.ALIGN_CENTER; template.AddImage(logo, w, 0, 0, h, 0, 0); cb.AddTemplate(template, pageSize.GetLeft(0), pageSize.GetBottom(0)); //cb.BeginText(); //cb.SetFontAndSize(bf, 8); //cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, // "Printed On " + PrintTime.ToString(), // pageSize.GetRight(40), // pageSize.GetBottom(30), 0); //cb.EndText(); }
public void DrawImage(Bitmap2 image, float x, float y, float width, float height) { Image img = null; try { img = Image.GetInstance(GraphUtils.ToBitmap(image), System.Drawing.Imaging.ImageFormat.Tiff); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } if (img != null) { img.ScaleAbsolute(width, height); img.SetAbsolutePosition(x, currentHeight - img.ScaledHeight - y); template.AddImage(img); } }
// --------------------------------------------------------------------------- public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 Image img = Image.GetInstance( Path.Combine(Utility.ResourceImage, RESOURCE) ); float w = img.ScaledWidth; float h = img.ScaledHeight; PdfTemplate t = writer.DirectContent.CreateTemplate(850, 600); t.Ellipse(0, 0, 850, 600); t.Clip(); t.NewPath(); t.AddImage(img, w, 0, 0, h, 0, -600); Image clipped = Image.GetInstance(t); clipped.ScalePercent(50); document.Add(clipped); } return(ms.ToArray()); } }
static private PdfTemplate CreateImageTemplate(PdfContentByte over, string imageFile) { iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageFile); img.SetAbsolutePosition(0, 0); PdfTemplate template = over.CreateTemplate(img.Width, img.Height); template.AddImage(img); return(template); }
public Image cropImage(Image image, PdfWriter writer, float fromLeft, float fromBottom, float width, float height) { // from https://stackoverflow.com/a/14473667 PdfContentByte cb = writer.DirectContent; PdfTemplate t = cb.CreateTemplate(width, height); float origWidth = image.ScaledWidth; float origHeight = image.ScaledHeight; t.AddImage(image, origWidth, 0, 0, origHeight, -fromLeft, -fromBottom); return(Image.GetInstance(t)); }
static void AddWatermake(Document doc, PdfWriter _write, Image img, string txt) { float _w = doc.Right - doc.Left; float _h = doc.Top - doc.Bottom; PdfTemplate template = PdfTemplate.CreateTemplate(_write, _w, _h); img.GrayFill = 100; img.SetAbsolutePosition(_w / 2 - (img.Width / 2), _h / 2 - (img.Height / 2)); template.AddImage(img, img.Width, 0, 0, img.Height, 0, 0); //ColumnText.ShowTextAligned(template, Element.ALIGN_CENTER, GetPhrase(txt, PDFFONTFAMILY.宋体, 12), _w / 2, _h / 2, 30); doc.Add(Image.GetInstance(template)); }
// Escribimos el header al inicio de cada página public override void OnStartPage(PdfWriter writer, Document document) { Image headerImage = ImageReport.GetHeader("Header/drawable-hdpi/Header"); //headerImage.SetAbsolutePosition(-280, 700); headerImage.SetAbsolutePosition(-230, 0); PdfContentByte cbhead = writer.DirectContent; PdfTemplate tp = cbhead.CreateTemplate(500, 500); tp.AddImage(headerImage); cbhead.AddTemplate(tp, -20, 700); //base.OnStartPage(writer, document); header.WriteSelectedRows(0, -1, 5, 780, writer.DirectContent); }
public static byte[] getPdf(string html, string css) { byte[] array; Image instance = Image.GetInstance(HttpContext.Current.Server.MapPath("~/images/logobav_edocta.jpg")); instance.SetAbsolutePosition(0f, 0f); instance.ScalePercent(72f); using (MemoryStream memoryStream = new MemoryStream()) { using (Document document = new Document(PageSize.LETTER)) { using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStream)) { document.Open(); try { try { using (MemoryStream memoryStream1 = new MemoryStream(Encoding.UTF8.GetBytes(css))) { using (MemoryStream memoryStream2 = new MemoryStream(Encoding.UTF8.GetBytes(html))) { XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, document, memoryStream2, memoryStream1); PdfContentByte directContent = pdfWriter.DirectContent; PdfTemplate pdfTemplate = directContent.CreateTemplate(644f, 52f); pdfTemplate.AddImage(instance); directContent.AddTemplate(pdfTemplate, 0f, 747f); } } } catch (Exception exception) { } } finally { document.Close(); } } } array = memoryStream.ToArray(); } return(array); }
// I am following a tutorial & they said that if I want to create headers/footers when each page is created // that I should override the OnEndPage() not the OnStartPage() is that correct? public override void OnEndPage(PdfWriter writer, Document document) { // Post: When each new page is created, add a header & footer image to the page. And set the top margin to 370px // and the bottom margin to 664px. // Result: The function executes but the pdf's header image isn't visible & the footer looks resized(scaled up in size). string path = System.Reflection.Assembly.GetExecutingAssembly().Location; var directory = System.IO.Path.GetDirectoryName(path); //Footer Image Image imgfoot = Image.GetInstance(directory + "/images/pdf/StadaFooter.jpg"); //Header Image Image imghead = Image.GetInstance(directory + "/images/pdf/StadaLogo.jpg"); imgfoot.SetAbsolutePosition(0, 0); imgfoot.ScaleAbsolute(new Rectangle(document.PageSize.Width, 60)); imghead.SetAbsolutePosition(0, 0); imghead.ScaleAbsolute(new Rectangle(document.PageSize.Width, 15)); PdfContentByte cbhead = writer.DirectContent; PdfTemplate tp = cbhead.CreateTemplate(document.PageSize.Width, document.PageSize.Height); // units are in pixels but I'm not sure if thats the correct units tp.AddImage(imghead); PdfContentByte cbfoot = writer.DirectContent; PdfTemplate tpl = cbfoot.CreateTemplate(document.PageSize.Width, document.PageSize.Height); tpl.AddImage(imgfoot); cbhead.AddTemplate(tp, 0, document.PageSize.Height); cbfoot.AddTemplate(tpl, 0, 0); //cbhead.AddTemplate(tp, 0, 715); helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); /*PdfContentByte cb = writer.DirectContent; * cbfoot.SaveState(); * document.SetMargins(35, 35, 100, 82); * cb.RestoreState();*/ //document.NewPage(); base.OnStartPage(writer, document); }
/// <summary> /// Apply background image to the added templates /// </summary> /// <param name="document">PDF Document</param> public void ApplyBackgroundImage(Document document) { var path = PageSetup.PagePreferences.BackgroundImageFilePath; var position = PageSetup.PagePreferences.BackgroundImagePosition; if (string.IsNullOrEmpty(path)) { return; } var img = path.GetITextSharpImageFromImageFile(); img.Alignment = Image.UNDERLYING; if (position == null) { img.SetAbsolutePosition((document.PageSize.Width - img.Width) / 2, (document.PageSize.Height - img.Height) / 2); } else { img.SetAbsolutePosition(position.Value.X, position.Value.Y); } _backgroundImageTemplate.AddImage(img); }
public void DownloadPDFFormat() { log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { Document pdfReport = new Document(PageSize.A4, 100, 91, 100, 93); System.IO.MemoryStream msReport = new System.IO.MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport); pdfReport.Open(); DBConnectionHandler1 db = new DBConnectionHandler1(); SqlConnection cn = db.getconnection(); cn.Open(); SqlCommand cmd = new SqlCommand("select * from UploadLogo", cn); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { if (dr.GetString(1).ToString() != "") { iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(@dr.GetString(1).ToString().Trim()); image1.SetAbsolutePosition(70, 100); PdfContentByte by = writer.DirectContent; PdfTemplate tp = by.CreateTemplate(170, 190); tp.AddImage(image1); by.AddTemplate(tp, 175, 660); dr.Close(); cn.Close(); } } string datetime = string.Empty; datetime = Convert.ToString(System.DateTime.Now); //Create Heading Phrase headerPhrase = new Phrase(" Recent Check-In Report ", FontFactory.GetFont("Garamond", 14)); headerPhrase.Add(" Generated On : "); headerPhrase.Add(datetime); HeaderFooter header = new HeaderFooter(headerPhrase, false); header.Border = Rectangle.NO_BORDER; header.Alignment = Element.ALIGN_CENTER; header.Alignment = Element.ALIGN_BOTTOM; pdfReport.Header = header; pdfReport.Add(headerPhrase); // Creates the Table PdfPTable ptData = new PdfPTable(gvItemTable.Columns.Count); ptData.SpacingBefore = 8; ptData.DefaultCell.Padding = 1; float[] headerwidths = new float[gvItemTable.Columns.Count]; // percentage headerwidths[0] = 3.2F; headerwidths[1] = 3.2F; headerwidths[2] = 3.2F; headerwidths[3] = 3.2F; headerwidths[4] = 3.2F; headerwidths[5] = 3.2F; // headerwidths[6] = 3.2F; //headerwidths[7] = 3.2F; //headerwidths[8] = 3.2F; //headerwidths[9] = 3.2F; //headerwidths[10] = 3.2F; ptData.SetWidths(headerwidths); ptData.WidthPercentage = 100; ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED; ptData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE; //Insert the Table Headers for (int intK = 0; intK < gvItemTable.Columns.Count; intK++) { PdfPCell cell = new PdfPCell(); cell.BorderWidth = 0.001f; cell.BackgroundColor = new Color(200, 200, 200); cell.BorderColor = new Color(100, 100, 100); cell.Phrase = new Phrase(gvItemTable.Columns[intK].HeaderText.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7, Font.BOLD)); ptData.AddCell(cell); } ptData.HeaderRows = 1; // this is the end of the table header //Insert the Table Data for (int intJ = 0; intJ < gvItemTable.Items.Count; intJ++) { for (int intK = 0; intK < gvItemTable.Columns.Count; intK++) { PdfPCell cell = new PdfPCell(); cell.BorderWidth = 0.001f; cell.BorderColor = new Color(100, 100, 100); cell.BackgroundColor = new Color(250, 250, 250); if (gvItemTable.Items[intJ].Cells[intK + 2].Text.ToString() != " ") { cell.Phrase = new Phrase(gvItemTable.Items[intJ].Cells[intK + 2].Text.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6)); } else { cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6)); } ptData.AddCell(cell); } } //Insert the Table pdfReport.Add(ptData); //Closes the Report and writes to Memory Stream pdfReport.Close(); //Writes the Memory Stream Data to Response Object Response.Clear(); // Response.AddHeader("content-disposition", string.Format("attachment;filename=" + ConfigurationManager.AppSettings["TxnInfoPdfFile"])); Response.AddHeader("content-disposition", string.Format("attachment;filename=RecentCheckedIn.pdf")); Response.Charset = ""; Response.ContentType = "application/pdf"; Response.BinaryWrite(msReport.ToArray()); Response.End(); } catch (Exception ex) { logger.Info(ex.Message); } }
public static void SignHashed(MemoryStream Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, Image img, int nroHojaFirma, string path, float h, string att_1, string att_2, string att_3, string url_terminos) { try { X509CertificateParser objCP = new X509CertificateParser(); X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1"); PdfReader objReader = new PdfReader(Source); //string[] msg = Certificate.SubjectName.Name.Split(','); //Document document = new Document(PageSize.A4, 50, 50, 150, 100); //PdfWriter pdfwritter = PdfWriter.GetInstance(document, new FileStream("C:\\Users\\Public\\terminos_condiciones.pdf", FileMode.OpenOrCreate)); using (PdfReader readerTerm = new PdfReader(url_terminos)) using (MemoryStream workStream = new MemoryStream()) { PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.OpenOrCreate, FileAccess.Write), '\0'); int nroPages = objReader.NumberOfPages + 1; Rectangle rectangle = readerTerm.GetPageSize(1); objStamper.InsertPage(nroPages, rectangle); PdfImportedPage bg = objStamper.GetImportedPage(readerTerm, 1); objStamper.GetUnderContent(nroPages).AddTemplate(bg, 0, 0); PdfSignatureAppearance objSA = objStamper.SignatureAppearance; img.ScaleAbsolute(120f, 60f); img.SetAbsolutePosition(0, 28); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); BaseFont bfBold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false); if (true) { objSA.SetVisibleSignature(new Rectangle(50, h - 120, 200, h), nroHojaFirma, "Firma Digital emitida por el sistema BV Digital"); } PdfTemplate n2Layer = objSA.GetLayer(2); n2Layer.BeginText(); n2Layer.SetFontAndSize(bfBold, 7); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Inspectorate Services Perú S.A.C", 0, 100, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "A Bureau Veritas Group Company", 0, 90, 0); n2Layer.EndText(); n2Layer.AddImage(img); n2Layer.BeginText(); n2Layer.SetFontAndSize(bf, 7); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Firmado Digitalmente por", 0, 40, 0); //string user = msg[2].Substring(msg[2].IndexOf('=') + 1); //user += " " + msg[3].Substring(msg[3].IndexOf('=') + 1); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_3, 0, 30, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Fecha: " + objSA.SignDate.ToString(), 0, 20, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_1, 0, 10, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_2, 0, 0, 0); n2Layer.EndText(); objSA.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; MakeSignature.SignDetached(objSA, externalSignature, objChain, null, null, null, 0, CryptoStandard.CMS); objStamper.SetFullCompression(); } } catch (Exception e) { Utility.log_err.save(null, e); } }
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; /* * 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; PdfPCell header7 = new PdfPCell(new Phrase(8, "Total USD: " + total, arial)); header7.HorizontalAlignment = 1; //TITULO,NUMERO Y FECHA table.AddCell(header); table.AddCell(header4); table.AddCell(header3); table.AddCell(header5); table.AddCell(header6); table.AddCell(header7); 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 cliente 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("CLIENTE:", arial)); cte.Border = 0; cte.VerticalAlignment = Element.ALIGN_CENTER; tablaCte.AddCell(cte); PdfPCell cte2 = new PdfPCell(new Phrase(NombreCte, 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 vendedor = new PdfPCell(new Phrase("VENDEDOR:", arial)); vendedor.Border = 0; vendedor.VerticalAlignment = Element.ALIGN_CENTER; tablaCte.AddCell(vendedor); PdfPCell vendedor2 = new PdfPCell(new Phrase(NombreVendedor, arial2)); vendedor2.Border = 0; vendedor2.VerticalAlignment = Element.ALIGN_CENTER; tablaCte.AddCell(vendedor2); PdfPCell proyecto = new PdfPCell(new Phrase("PROYECTO:", arial)); proyecto.Border = 0; proyecto.VerticalAlignment = Element.ALIGN_CENTER; tablaCte.AddCell(proyecto); PdfPCell proyecto2 = new PdfPCell(new Phrase(NombreProyecto, 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 cliente #region Titulos de Columnas PdfPTable NombreColumnas = new PdfPTable(4); NombreColumnas.TotalWidth = document.PageSize.Width - 90f; NombreColumnas.LockedWidth = true; NombreColumnas.WidthPercentage = 70; float[] widths2 = new float[] { 1f, 4f, 8f, 1f }; 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); 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 override void OnStartPage(PdfWriter writer, Document document) { base.OnStartPage(writer, document); Rectangle pageSize = document.PageSize; if (Title != string.Empty) { cb.BeginText(); cb.SetFontAndSize(bf, 15); cb.SetRgbColorFill(50, 50, 200); cb.SetColorFill(new BaseColor(103, 93, 152)); //cb.SetRgbColorFillF(103, 93, 152); WriteWaterMark(document, "sss"); cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetTop(40)); cb.ShowText(Title); cb.EndText(); } if (HeaderLeft + HeaderRight != string.Empty) { //PdfPTable HeaderTable = new PdfPTable(2); //HeaderTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE; //HeaderTable.TotalWidth = pageSize.Width; //HeaderTable.SetWidthPercentage(new float[] { 50, 50 }, pageSize); //PdfPCell HeaderLeftCell = new PdfPCell(new Phrase(8, HeaderLeft, HeaderFont)) { BorderColor = new BaseColor(54, 207, 37), BackgroundColor = new BaseColor(54, 207, 37) }; //HeaderLeftCell.Padding = 5; //HeaderLeftCell.PaddingBottom = 8; //HeaderLeftCell.BorderWidthRight = 0; ////HeaderLeftCell.BackgroundColor = new BaseColor(103, 93, 152); //HeaderTable.AddCell(HeaderLeftCell); //PdfPCell HeaderRightCell = new PdfPCell(new Phrase(8, HeaderRight, HeaderFont)) { BorderColor = new BaseColor(237, 77, 7), BackgroundColor = new BaseColor(237, 77, 7) }; //HeaderRightCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; //HeaderRightCell.Padding = 5; //HeaderRightCell.PaddingBottom = 8; //HeaderRightCell.BorderWidthLeft = 0; //HeaderTable.AddCell(HeaderRightCell); //cb.SetRgbColorFill(0, 0, 0); //HeaderTable.WriteSelectedRows(0, -1, pageSize.GetLeft(0), pageSize.GetTop(0), cb); } iTextSharp.text.Image logo = null; if (_FlagModulo == "SIM") { logo = iTextSharp.text.Image.GetInstance(Path.Combine(Environment.CurrentDirectory, "img", "header-sim.png")); } else if (_FlagModulo == "SINMI") { logo = iTextSharp.text.Image.GetInstance(Path.Combine(Environment.CurrentDirectory, "img", "header-sinmi.png")); } else { logo = iTextSharp.text.Image.GetInstance(Path.Combine(Environment.CurrentDirectory, "img", "header.png")); } float w = document.PageSize.Width; float h = 80; logo.Alignment = Element.ALIGN_CENTER; templateHeader.AddImage(logo, w, 0, 0, h, 0, 0); cb.AddTemplate(templateHeader, pageSize.GetLeft(0), pageSize.GetTop(80)); }
/// <summary> /// </summary> /// <param name="writer"></param> /// <param name="document"></param> /// Called when a page is finished, just before being written to the document. /// @param writer the <CODE>PdfWriter</CODE> for this document /// @param document the document public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); var FontColour = new BaseColor(216, 84, 89); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLUE); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, FontColour); Phrase p1Header = new Phrase(this.setting.Header, baseFontBig); Phrase p2Header = new Phrase(this.setting.SubHeader, 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 //Uri uri = new Uri(); //Image ima; //ima.Url = uri; String path = System.Web.HttpContext.Current.Server.MapPath("~/Images/" + this.setting.Logo).ToString(); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path); image.SetAbsolutePosition(0, 20); image.ScaleAbsolute(60, 50); image.Alignment = iTextSharp.text.Image.ALIGN_LEFT; PdfContentByte cbhead = writer.DirectContent; PdfTemplate tp = cbhead.CreateTemplate(273, 95); tp.AddImage(image); cbhead.AddTemplate(tp, 60, 842 - 95); PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(p1Header); PdfPCell pdfCell3 = new PdfPCell(); String text = "Page " + writer.PageNumber + " of "; //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(p2Header); PdfPCell pdfCell7 = new PdfPCell(); //Row 3 if (this.setting.ShowDate) { pdfCell7 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig)); } PdfPCell pdfCell6 = new PdfPCell(); PdfPCell pdfCell5 = new PdfPCell(); //PdfPCell pdfCell7 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), 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 - 90); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 90); 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(); }
/// <summary> /// Exporta tabela e adiociona uma linha no cabelaho de produção com datas de exportações /// </summary> /// <param name="strPdfPath">Caminho a ser salvo o PDF </param> /// <param name="strHeader">O que será escrito no cabeçalho da página</param> /// <param name="dataExportacaoInicial"> Envia uma data para ser salvo no PDF e para mostrar quando foi iniciado a exportação</param> /// <param name="dataExportacaoFinal"> Envia uma data para ser salvo no PDF e para mostrar quando foi finalizado a exportação</param> public static bool exportProducao(String strPdfPath, string strHeader, DateTime dataExportacaoInicial, DateTime dataExportacaoFinal) { try { #region Váriveis float[] colsW = { 25, 25 }; #endregion #region Cabeçalho System.IO.FileStream fs = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None); Document document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, fs); writer.PageEvent = new PDFFooter(); document.Open(); //Report Header BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntHead = new Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.BLACK); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead)); document.Add(prgHeading); //Adiociona a imagem no projeto e no PDF #region Imagem Automasul //Busca a imagem string filename = "Logo_Automasul.png"; //Salva a imagem no arquivo Bin Resources.Logo_Automasul.Save(Path.GetFullPath(filename)); string path = Path.GetFullPath(filename); //Manda o caminho para o PDF iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path); image.SetAbsolutePosition(0, 20); image.ScaleAbsolute(150, 50); image.Alignment = iTextSharp.text.Image.ALIGN_LEFT; PdfContentByte cbhead = writer.DirectContent; PdfTemplate tp = cbhead.CreateTemplate(1000, 1000); tp.AddImage(image); cbhead.AddTemplate(tp, 0, 842 - 95); #endregion //Adiociona a imagem no projeto e no PDF #region Imagem Becker //Busca a imagem string filename1 = "Logo_Automasul.png"; //Salva a imagem no arquivo Bin Resources.Logo_Automasul.Save(Path.GetFullPath(filename1)); string path1 = Path.GetFullPath(filename1); //Manda o caminho para o PDF iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(path1); image1.SetAbsolutePosition(460, 40); image1.ScaleAbsolute(100, 30); image1.Alignment = iTextSharp.text.Image.ALIGN_RIGHT; PdfContentByte cbhead1 = writer.DirectContent; PdfTemplate tp1 = cbhead1.CreateTemplate(1000, 1000); tp1.AddImage(image1); cbhead1.AddTemplate(tp1, 0, 842 - 95); #endregion //Author Paragraph prgAuthor = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntAuthor = new Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.GRAY); prgAuthor.Alignment = Element.ALIGN_RIGHT; prgAuthor.Add(new Chunk("Autor : " + Utilidades.VariaveisGlobais.UserLogged_GS, fntAuthor)); prgAuthor.Add(new Chunk("\nExportado : " + DateTime.Now.ToShortDateString(), fntAuthor)); document.Add(prgAuthor); //Add a line seperation Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); document.Add(p); //Add line break //document.Add(new Chunk("\n", fntHead)); #endregion DataTable DataProducao = new DataTable(); DataProducao = returnProducao(dataExportacaoInicial, dataExportacaoFinal); foreach (DataRow row in DataProducao.Rows) { document.Add(tableProducao("Produção N°: " + row[0].ToString() + ", Receita: " + row[8].ToString(), false, Element.ALIGN_CENTER)); document.Add(tableProducao(colsW, "Peso total produzido: " + Math.Round(Convert.ToSingle(row[2].ToString()), 2) + " kg", "Peso esperado producao: " + Math.Round(Convert.ToSingle(row[1].ToString()), 2) + " kg", false)); document.Add(tableProducao(colsW, "Data início produção: " + row[3].ToString(), "Data fim produção: " + row[4].ToString(), false)); //Add a line seperation Paragraph p1 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); document.Add(p1); //Adiocona o detatalhamento da Produção Paragraph Detalhamento = new Paragraph(); BaseFont btnDetalhamento = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntADetalhamento = FontFactory.GetFont(BaseFont.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0)); Detalhamento.Alignment = Element.ALIGN_CENTER; Detalhamento.Add(new Chunk("Detalhamento Produção", fntADetalhamento)); document.Add(Detalhamento); document.Add(new Chunk("\n", fntHead)); PdfPTable tablebatelada = new PdfPTable(4); BaseColor preto = new BaseColor(0, 0, 0); BaseColor fundo = new BaseColor(200, 200, 200); BaseColor branco = new BaseColor(255, 255, 255); Font font = FontFactory.GetFont(BaseFont.TIMES_ROMAN, 10, Font.BOLD, preto); Font titulo = FontFactory.GetFont(BaseFont.TIMES_ROMAN, 10, Font.BOLD, preto); float[] colsWBatelada = { 20, 20, 20, 20 }; tablebatelada.HeaderRows = 0; tablebatelada.WidthPercentage = 100f; tablebatelada.DefaultCell.Border = PdfPCell.BOX; tablebatelada.DefaultCell.BorderColor = new BaseColor(255, 255, 255); tablebatelada.DefaultCell.BorderColorBottom = new BaseColor(255, 255, 255); tablebatelada.DefaultCell.Padding = 5; tablebatelada.AddCell(getNewCell("Desrição Produto", titulo, Element.ALIGN_CENTER, 5, PdfPCell.BOX, preto, branco)); tablebatelada.AddCell(getNewCell("Peso Desejado", titulo, Element.ALIGN_CENTER, 5, PdfPCell.BOX, preto, branco)); tablebatelada.AddCell(getNewCell("Peso Dosado", titulo, Element.ALIGN_CENTER, 5, PdfPCell.BOX, preto, branco)); tablebatelada.AddCell(getNewCell("Percentual de Tolerância", titulo, Element.ALIGN_CENTER, 5, PdfPCell.BOX, preto, branco)); DataTable DataProducaoProdutos = new DataTable(); DataProducaoProdutos = returnProdutosProducao(Convert.ToInt32(row[0].ToString())); foreach (DataRow rowProdutos in DataProducaoProdutos.Rows) { tablebatelada.AddCell(getNewCell(rowProdutos[2].ToString(), font, Element.ALIGN_LEFT, 5, PdfPCell.BOX)); tablebatelada.AddCell(getNewCell(rowProdutos[6].ToString() + " kg", font, Element.ALIGN_LEFT, 5, PdfPCell.BOX)); tablebatelada.AddCell(getNewCell(rowProdutos[7].ToString() + " kg", font, Element.ALIGN_LEFT, 5, PdfPCell.BOX)); tablebatelada.AddCell(getNewCell(rowProdutos[8].ToString() + " %", font, Element.ALIGN_LEFT, 5, PdfPCell.BOX)); } tablebatelada.KeepTogether = true; document.Add(tablebatelada); document.Add(new Chunk("\n", fntHead)); } document.Close(); writer.Close(); fs.Close(); return(true); } catch (Exception ex) { Utilidades.VariaveisGlobais.Window_Buffer_Diagnostic.List_Error = ex.ToString() + " Erro exportar relatório Produção"; return(false); } }
/** * Gets the button appearance. * @throws IOException on error * @throws DocumentException on error * @return the button appearance */ public PdfAppearance GetAppearance() { PdfAppearance app = GetBorderAppearance(); Rectangle box = new Rectangle(app.BoundingBox); if ((text == null || text.Length == 0) && (layout == LAYOUT_LABEL_ONLY || (image == null && template == null && iconReference == null))) { return app; } if (layout == LAYOUT_ICON_ONLY && image == null && template == null && iconReference == null) return app; BaseFont ufont = RealFont; bool borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET; float h = box.Height - borderWidth * 2; float bw2 = borderWidth; if (borderExtra) { h -= borderWidth * 2; bw2 *= 2; } float offsetX = (borderExtra ? 2 * borderWidth : borderWidth); offsetX = Math.Max(offsetX, 1); float offX = Math.Min(bw2, offsetX); tp = null; float textX = float.NaN; float textY = 0; float fsize = fontSize; float wt = box.Width - 2 * offX - 2; float ht = box.Height - 2 * offX; float adj = (iconFitToBounds ? 0 : offX + 1); int nlayout = layout; if (image == null && template == null && iconReference == null) nlayout = LAYOUT_LABEL_ONLY; Rectangle iconBox = null; while (true) { switch (nlayout) { case LAYOUT_LABEL_ONLY: case LAYOUT_LABEL_OVER_ICON: if (text != null && text.Length > 0 && wt > 0 && ht > 0) { fsize = CalculateFontSize(wt, ht); textX = (box.Width - ufont.GetWidthPoint(text, fsize)) / 2; textY = (box.Height - ufont.GetFontDescriptor(BaseFont.ASCENT, fsize)) / 2; } goto case LAYOUT_ICON_ONLY; case LAYOUT_ICON_ONLY: if (nlayout == LAYOUT_LABEL_OVER_ICON || nlayout == LAYOUT_ICON_ONLY) iconBox = new Rectangle(box.Left + adj, box.Bottom + adj, box.Right - adj, box.Top - adj); break; case LAYOUT_ICON_TOP_LABEL_BOTTOM: if (text == null || text.Length == 0 || wt <= 0 || ht <= 0) { nlayout = LAYOUT_ICON_ONLY; continue; } float nht = box.Height * 0.35f - offX; if (nht > 0) fsize = CalculateFontSize(wt, nht); else fsize = 4; textX = (box.Width - ufont.GetWidthPoint(text, fsize)) / 2; textY = offX - ufont.GetFontDescriptor(BaseFont.DESCENT, fsize); iconBox = new Rectangle(box.Left + adj, textY + fsize, box.Right - adj, box.Top - adj); break; case LAYOUT_LABEL_TOP_ICON_BOTTOM: if (text == null || text.Length == 0 || wt <= 0 || ht <= 0) { nlayout = LAYOUT_ICON_ONLY; continue; } nht = box.Height * 0.35f - offX; if (nht > 0) fsize = CalculateFontSize(wt, nht); else fsize = 4; textX = (box.Width - ufont.GetWidthPoint(text, fsize)) / 2; textY = box.Height - offX - fsize; if (textY < offX) textY = offX; iconBox = new Rectangle(box.Left + adj, box.Bottom + adj, box.Right - adj, textY + ufont.GetFontDescriptor(BaseFont.DESCENT, fsize)); break; case LAYOUT_LABEL_LEFT_ICON_RIGHT: if (text == null || text.Length == 0 || wt <= 0 || ht <= 0) { nlayout = LAYOUT_ICON_ONLY; continue; } float nw = box.Width * 0.35f - offX; if (nw > 0) fsize = CalculateFontSize(wt, nw); else fsize = 4; if (ufont.GetWidthPoint(text, fsize) >= wt) { nlayout = LAYOUT_LABEL_ONLY; fsize = fontSize; continue; } textX = offX + 1; textY = (box.Height - ufont.GetFontDescriptor(BaseFont.ASCENT, fsize)) / 2; iconBox = new Rectangle(textX + ufont.GetWidthPoint(text, fsize), box.Bottom + adj, box.Right - adj, box.Top - adj); break; case LAYOUT_ICON_LEFT_LABEL_RIGHT: if (text == null || text.Length == 0 || wt <= 0 || ht <= 0) { nlayout = LAYOUT_ICON_ONLY; continue; } nw = box.Width * 0.35f - offX; if (nw > 0) fsize = CalculateFontSize(wt, nw); else fsize = 4; if (ufont.GetWidthPoint(text, fsize) >= wt) { nlayout = LAYOUT_LABEL_ONLY; fsize = fontSize; continue; } textX = box.Width - ufont.GetWidthPoint(text, fsize) - offX - 1; textY = (box.Height - ufont.GetFontDescriptor(BaseFont.ASCENT, fsize)) / 2; iconBox = new Rectangle(box.Left + adj, box.Bottom + adj, textX - 1, box.Top - adj); break; } break; } if (textY < box.Bottom + offX) textY = box.Bottom + offX; if (iconBox != null && (iconBox.Width <= 0 || iconBox.Height <= 0)) iconBox = null; bool haveIcon = false; float boundingBoxWidth = 0; float boundingBoxHeight = 0; PdfArray matrix = null; if (iconBox != null) { if (image != null) { tp = new PdfTemplate(writer); tp.BoundingBox = new Rectangle(image); writer.AddDirectTemplateSimple(tp, PdfName.FRM); tp.AddImage(image, image.Width, 0, 0, image.Height, 0, 0); haveIcon = true; boundingBoxWidth = tp.BoundingBox.Width; boundingBoxHeight = tp.BoundingBox.Height; } else if (template != null) { tp = new PdfTemplate(writer); tp.BoundingBox = new Rectangle(template.Width, template.Height); writer.AddDirectTemplateSimple(tp, PdfName.FRM); tp.AddTemplate(template, template.BoundingBox.Left, template.BoundingBox.Bottom); haveIcon = true; boundingBoxWidth = tp.BoundingBox.Width; boundingBoxHeight = tp.BoundingBox.Height; } else if (iconReference != null) { PdfDictionary dic = (PdfDictionary)PdfReader.GetPdfObject(iconReference); if (dic != null) { Rectangle r2 = PdfReader.GetNormalizedRectangle(dic.GetAsArray(PdfName.BBOX)); matrix = dic.GetAsArray(PdfName.MATRIX); haveIcon = true; boundingBoxWidth = r2.Width; boundingBoxHeight = r2.Height; } } } if (haveIcon) { float icx = iconBox.Width / boundingBoxWidth; float icy = iconBox.Height / boundingBoxHeight; if (proportionalIcon) { switch (scaleIcon) { case SCALE_ICON_IS_TOO_BIG: icx = Math.Min(icx, icy); icx = Math.Min(icx, 1); break; case SCALE_ICON_IS_TOO_SMALL: icx = Math.Min(icx, icy); icx = Math.Max(icx, 1); break; case SCALE_ICON_NEVER: icx = 1; break; default: icx = Math.Min(icx, icy); break; } icy = icx; } else { switch (scaleIcon) { case SCALE_ICON_IS_TOO_BIG: icx = Math.Min(icx, 1); icy = Math.Min(icy, 1); break; case SCALE_ICON_IS_TOO_SMALL: icx = Math.Max(icx, 1); icy = Math.Max(icy, 1); break; case SCALE_ICON_NEVER: icx = icy = 1; break; default: break; } } float xpos = iconBox.Left + (iconBox.Width - (boundingBoxWidth * icx)) * iconHorizontalAdjustment; float ypos = iconBox.Bottom + (iconBox.Height - (boundingBoxHeight * icy)) * iconVerticalAdjustment; app.SaveState(); app.Rectangle(iconBox.Left, iconBox.Bottom, iconBox.Width, iconBox.Height); app.Clip(); app.NewPath(); if (tp != null) app.AddTemplate(tp, icx, 0, 0, icy, xpos, ypos); else { float cox = 0; float coy = 0; if (matrix != null && matrix.Size == 6) { PdfNumber nm = matrix.GetAsNumber(4); if (nm != null) cox = nm.FloatValue; nm = matrix.GetAsNumber(5); if (nm != null) coy = nm.FloatValue; } app.AddTemplateReference(iconReference, PdfName.FRM, icx, 0, 0, icy, xpos - cox * icx, ypos - coy * icy); } app.RestoreState(); } if (!float.IsNaN(textX)) { app.SaveState(); app.Rectangle(offX, offX, box.Width - 2 * offX, box.Height - 2 * offX); app.Clip(); app.NewPath(); if (textColor == null) app.ResetGrayFill(); else app.SetColorFill(textColor); app.BeginText(); app.SetFontAndSize(ufont, fsize); app.SetTextMatrix(textX, textY); app.ShowText(text); app.EndText(); app.RestoreState(); } return app; }
static public bool PlaceImageOnLabel(string input, string output, string label, string imgFile, string widthParam, string heightParam, bool center) { if (!File.Exists(input)) { throw new FileNotFoundException(FILE_NOT_FOUND, input); } if (!File.Exists(imgFile)) { throw new FileNotFoundException(FILE_IMAGE_NOT_FOUND, imgFile); } bool labelFinded = false; // Проверим параметры // widthParam, heightParam должны принимать значение "", null, fit, или число. bool scaleByWidth = false; bool scaleByHeight = false; float width = 0; float height = 0; int result; if (string.IsNullOrEmpty(widthParam)) { ; } // пропускаем else if (Int32.TryParse(widthParam, out result)) { width = result; scaleByWidth = true; } else if (widthParam == "fit") { scaleByWidth = true; } else { throw new ArgumentException(); } if (string.IsNullOrEmpty(heightParam)) { ; } // пропускаем else if (Int32.TryParse(heightParam, out result)) { height = result; scaleByHeight = true; } else if (heightParam == "fit") { scaleByHeight = true; } else { throw new ArgumentException(); } System.IO.FileStream fs = new FileStream(output, FileMode.Create); using (PdfReader pdfReader = new PdfReader(input)) { PdfStamper stamper = new PdfStamper(pdfReader, fs); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgFile); img.SetAbsolutePosition(0, 0); for (int page = 1; page <= pdfReader.NumberOfPages; page++) { var strategy = new PDFCompare.Comparer.LocationExtractionStrategy(); strategy.Page = page; PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy); List <PDFCompare.Comparer.TextItem> items = strategy.GetTextItems(); PdfContentByte over = stamper.GetOverContent(page); foreach (var item in items) { var word = item.Text; if (word == label) { float rotateDegrees = 0; Vector leftBottom = item.DescentLine.GetStartPoint(); Vector rightTop = item.AscentLine.GetEndPoint(); float offsetX = leftBottom[0]; float offsetY = leftBottom[1]; // GetPageSize - возвращает размер без учета ориентации(альбомная, вертикальная), т.е. в случае альбомной width и height // будут перепутаны при отображении на экране и позиционировании, поэтому нужно делать GetPageSizeWithRotation. iTextSharp.text.Rectangle pagesize = pdfReader.GetPageSizeWithRotation(page); PdfTemplate template = over.CreateTemplate(img.Width, img.Height); template.AddImage(img); var matrix = new System.Drawing.Drawing2D.Matrix(); // Трансформации применяются в обратном порядке // Vector v = item.DescentLine.GetEndPoint().Subtract(item.DescentLine.GetStartPoint()); rotateDegrees = (float)(Math.Atan2((double)v[1], (double)v[0]) * 180 / Math.PI); int pageRotation = pdfReader.GetPageRotation(page); // Если страница повернута, то мы получаем координаты на неповернутой странице, // а AddTemplate делает в координатах повернутой. // Поэтому преобразуем штамп обратно в координаты неповернутой. switch (pageRotation) { case 90: matrix.Translate(0, pagesize.Height); break; case 180: matrix.Translate(pagesize.Width, pagesize.Height); break; case 270: matrix.Translate(pagesize.Width, 0); break; } if (pageRotation != 0) { matrix.Rotate(360 - pageRotation); } // Сдвинем штрих код на свое место matrix.Translate(offsetX, offsetY); // Повернем штрихкод как текст повернут float w = (item.DescentLine.GetEndPoint().Subtract(item.DescentLine.GetStartPoint())).Length; // img.ScaleToFit(w, w*img.Height/img.Width); matrix.Rotate(rotateDegrees); // Отмасштабируем штрихкод чтобы вписать в п/у текста float widthLabel = width != 0 ? width : (item.DescentLine.GetEndPoint().Subtract(item.DescentLine.GetStartPoint())).Length; float heightLabel = height != 0 ? height : (item.AscentLine.GetStartPoint().Subtract(item.DescentLine.GetStartPoint())).Length; float scaleX = scaleByWidth ? widthLabel / img.Width : 0; float scaleY = scaleByHeight ? heightLabel / img.Height : 0; if (scaleX != 0 && scaleY == 0) { scaleY = scaleX; } if (scaleY != 0 && scaleX == 0) { scaleX = scaleY; } if (scaleX != 0 && scaleY != 0) { matrix.Scale(scaleX, scaleY); } // Применим шаблон и преобразования float[] elements = matrix.Elements; over.AddTemplate(template, elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]); labelFinded = true; } } } stamper.Close(); } return(labelFinded); }