public static MemoryStream GenerateSingleBadge(Guid Id, UnitOfWork unitOfWork) { Setting setting = GetSetting(unitOfWork); Registration reg = unitOfWork.RegistrationRepository.GetByID(Id); string pdfPath = setting.WebLocation + "Storage\\Pdf\\Badge.pdf"; PdfReader pdfReader = null; MemoryStream memoryStreamPdfStamper = null; PdfStamper pdfStamper = null; AcroFields pdfFormFields = null; pdfReader = new PdfReader(pdfPath); memoryStreamPdfStamper = new MemoryStream(); pdfStamper = new PdfStamper(pdfReader, memoryStreamPdfStamper); pdfFormFields = pdfStamper.AcroFields; pdfFormFields.SetField("name", reg.Name); // Barcode MemoryStream memoryStream = GenerateQrcode(reg.SerialNo, 119, 119); iTextSharp.text.Image img = null; PdfContentByte pdfContentByte = null; img = iTextSharp.text.Image.GetInstance(memoryStream); img.ScaleToFit(190, 30); pdfContentByte = pdfStamper.GetOverContent(1); img.SetAbsolutePosition(95f, 59f); pdfContentByte.AddImage(img); memoryStream = new MemoryStream(reg.Image); img = iTextSharp.text.Image.GetInstance(memoryStream); img.ScaleToFit(290, 120); pdfContentByte = pdfStamper.GetOverContent(1); img.SetAbsolutePosition(70f, 140f); pdfContentByte.AddImage(img); pdfStamper.FormFlattening = true; pdfStamper.Writer.CloseStream = false; pdfStamper.Close(); memoryStreamPdfStamper.Flush(); memoryStreamPdfStamper.Seek(0, SeekOrigin.Begin); //MemoryStream docstream = CreatePdfDoc(memoryStreamPdfStamper); //memoryStreamPdfStamper.Dispose(); //docstream.Position = 0; //return docstream; //memoryStreamPdfStamper.Position = 0; return(memoryStreamPdfStamper); }
private static void Render_FrontContent(PdfContentByte canvas, Member member) { Font f = new Font(baseFont, 12, Font.BOLD) { Color = BaseColor.WHITE }; int bottom = CARD_HEIGHT - (UPPER_BAR_HEIGHT + PHOTO_BAR_HEIGHT) - 12 - 2; Phrase p = new Phrase(member.FullName, f); ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0); bottom -= 14; f = new Font(baseFont, 12) { Color = BaseColor.WHITE }; p = new Phrase(member.WacLevel.ToString(), f); ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0); bottom -= 12; f = new Font(baseFont, 10, Font.BOLD) { Color = BaseColor.WHITE }; p = new Phrase("KCSO DEM# " + member.DEM, f); ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0); BarcodePDF417 barcode = new BarcodePDF417(); barcode.SetText(string.Format("Unknown Text. To be added. King County Search and Rescue{0}{1}{2}", member.LastName, member.FirstName, member.DEM)); barcode.CodeRows = 20; barcode.CodeColumns = 7; barcode.Options = BarcodePDF417.PDF417_FIXED_RECTANGLE; var img = barcode.GetImage(); img.ScaleAbsolute(CARD_WIDTH - 30, 28); img.SetAbsolutePosition((CARD_WIDTH - img.ScaledWidth) / 2, CARD_HEIGHT - UPPER_BAR_HEIGHT - PHOTO_BAR_HEIGHT - LOWER_BAR_HEIGHT - img.ScaledHeight - 8); canvas.AddImage(img); if (!string.IsNullOrWhiteSpace(member.PhotoFile)) { var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content", "auth", "members", member.PhotoFile); if (File.Exists(file)) { img = Image.GetInstance(file); img.ScaleToFit(PHOTO_WIDTH, PHOTO_BAR_HEIGHT); img.SetAbsolutePosition(CARD_WIDTH - img.ScaledWidth, CARD_HEIGHT - (UPPER_BAR_HEIGHT + img.ScaledHeight)); canvas.AddImage(img); } } }
public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); var currentPageNumber = writer.PageNumber; Rectangle pageSize = document.PageSize; var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); var pageNumberTextFormat = "Page {0} of "; var lengthOfPageNumberTextInBaseFont = baseFont.GetWidthPoint(pageNumberTextFormat, 10f); pdfContentByte.BeginText(); pdfContentByte.SetRGBColorFill(255, 100, 200); pdfContentByte.SetFontAndSize(baseFont, 10f); pdfContentByte.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30)); pdfContentByte.ShowText(string.Format(pageNumberTextFormat, currentPageNumber)); pdfContentByte.EndText(); pdfContentByte.AddTemplate(pdfTemplate, pageSize.GetLeft(40) + lengthOfPageNumberTextInBaseFont, pageSize.GetBottom(30)); pdfContentByte.AddImage(Image.GetInstance("C:\\temp\\Wintellect.png"), 80f, 180f, 0f, 38f, 250f, 20f); pdfContentByte.BeginText(); pdfContentByte.SetFontAndSize(baseFont, 10f); pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Printed On " + DateTime.Now.ToString(), pageSize.GetRight(40), pageSize.GetBottom(30), 0); pdfContentByte.EndText(); }
public void Write(Document document, PdfWriter writer, PdfContentByte pdfContent) { Image img = Image.GetInstance(_imgUri); img.SetAbsolutePosition(_absoluteX, _absoluteY); pdfContent.AddImage(img); }
public static void AddQRCode(this PdfContentByte pdfContentByte, float x, float y, string text, int size) { var image = new BarcodeQRCode(text, size, size, null).GetImage(); image.SetAbsolutePosition(x, y); pdfContentByte.AddImage(image); }
public void drawImage(PdfContentByte pcb, Graphics g2, Parser cp, int row, int col, float x, float y, float w, float h, bool isLean) { byte[] imgb = null; if (isLean) { imgb = (byte[])cp.getPropertyValue(row, col, 305); } else { imgb = (byte[])cp.getPropertyValue(row, col, 302); } if (imgb != null) { iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(imgb); int num2 = Convert.ToInt32(cp.getPropertyValue(row, col, 504)); int num = Convert.ToInt32(cp.getPropertyValue(row, col, 505)); if ((num2 > 0) && (num > 0)) { instance.ScaleAbsolute((float)num2, (float)num); this.method_0((int)x, (int)y, (int)w, (int)h, num2, num); } else if ((int)(cp.getPropertyValue(row, col, 309)) != PropertyDefine.CAS_FIXIMAGE) { this.method_0((int)x, (int)y, (int)w, (int)h, (int)instance.Width, (int)instance.Height); } else { instance.ScaleAbsolute(w, -1 * h); this.method_0((int)x, (int)y, (int)w, (int)h, (int)w, (int)(-1 * h)); } instance.SetAbsolutePosition((float)this.int_2, (float)(this.int_3 + this.int_5)); pcb.AddImage(instance); } }
/// <summary> /// 将TIF图片转化为PDF文件 /// </summary> /// <param name="tif_path">tif路径</param> /// <param name="pdf_path">pdf路径</param> public void TIF_PDF(string tif_path, string pdf_path) { Document pdfdoc = null; try { System.Drawing.Bitmap bm = new System.Drawing.Bitmap(tif_path); int total = bm.GetFrameCount(FrameDimension.Page); pdfdoc = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(pdf_path, FileMode.Create)); pdfdoc.Open(); PdfContentByte cb = writer.DirectContent; for (int k = 0; k < total; k++) { bm.SelectActiveFrame(FrameDimension.Page, k); Image img = Image.GetInstance(bm, null, true); img.ScalePercent(72f / 300f * 100); img.SetAbsolutePosition(0, 0); cb.AddImage(img); pdfdoc.NewPage(); } } catch (Exception e) { throw new Exception("TIF_PDF异常\r\n" + e.Message); } finally { if (pdfdoc != null) { pdfdoc.Close(); } } }
public sealed override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); if (HasWaterMarkText) { contentByte.SaveState(); contentByte.SetGState(state); ColumnText.ShowTextAligned( contentByte, Element.ALIGN_CENTER, new Phrase(waterMarkText, waterFont), 300, 400, 45 ); contentByte.RestoreState(); } if (HasWaterMarkImage) { waterMarkImage.ScaleToFit(document.PageSize); waterMarkImage.SetAbsolutePosition( (document.PageSize.Width - waterMarkImage.PlainWidth) / 2, (document.PageSize.Height - waterMarkImage.PlainHeight) / 2 ); contentByte.SaveState(); contentByte.SetGState(state); contentByte.AddImage(waterMarkImage); contentByte.RestoreState(); } }
public void GetChPdf(string templatePath, string newFilePath, Dictionary <string, string> parameters) { PdfReader pdfReader = new PdfReader(templatePath); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFilePath, FileMode.Create)); AcroFields acroFields = pdfStamper.AcroFields; BaseFont value = BaseFont.CreateFont("C:\\Windows\\Fonts\\simsun.ttc,0", "Identity-H", true); foreach (KeyValuePair <string, string> parameter in parameters) { acroFields.SetFieldProperty(parameter.Key, "textfont", value, null); acroFields.SetField(parameter.Key, parameter.Value); } for (int i = 0; i < CheckList.Count; i++) { int nDataLength = 0; DllImageFuc.GetImageDataRoiFunc(InfoStruct, SlideZoom, CheckList[i].GlobalPosX, CheckList[i].GlobalPosY, CheckList[i].Width, CheckList[i].Height, out IntPtr datas, ref nDataLength, true); byte[] array = new byte[nDataLength]; if (datas != IntPtr.Zero) { Marshal.Copy(datas, array, 0, nDataLength); } DllImageFuc.DeleteImageDataFunc(datas); iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(array); instance.ScaleAbsoluteWidth(40f); instance.ScaleAbsoluteHeight(40f); instance.SetAbsolutePosition(40 + i * 50 + 10, 400f); PdfContentByte overContent = pdfStamper.GetOverContent(1); overContent.AddImage(instance); } pdfStamper.FormFlattening = true; pdfStamper.Close(); pdfReader.Close(); }
public string SignFile(byte[] fileToSign, int documentID, int pageNumber, byte[] userSignature, float x, float y) { var stream = new MemoryStream(fileToSign); PdfReader pdfReader = new PdfReader(stream); var newFile = new MemoryStream(); PdfStamper pdfStamper = new PdfStamper(pdfReader, newFile); //Image image = Image.GetInstance(Path.Combine(pathToResources, "Matt Signature.png")); Image image = Image.GetInstance(userSignature.ToArray()); image.ScaleAbsolute(150f, 75f); PdfContentByte content = pdfStamper.GetOverContent(pageNumber); //image.SetAbsolutePosition(pdfReader.GetPageSize(1).Width * x, pdfReader.GetPageSize(1).Height * y); //image.SetAbsolutePosition(content.co, 0f); image.SetAbsolutePosition(PageSize.LETTER.Width * (x * .9f), PageSize.LETTER.Height * (1 - y)); //image.SetAbsolutePosition(PageSize.LETTER.Width - image.ScaledWidth, 0); content.AddImage(image); pdfStamper.Close(); var stamp = $"http://signme/Documents/{documentID}"; var final = AddWaterMark(newFile.ToArray(), $"Signed {DateTime.Now.ToString("d")} "); var final2 = ApplyVerificationStamp2(final.ToArray(), stamp); return(Convert.ToBase64String(final2.ToArray())); }
private static void GenerateTextTemplate(PdfContentByte Pcb, Parent STD) { Pcb.BeginText(); Image Logo = Image.GetInstance(@"C:\Users\Chase charsley\Documents\Chase\BULAWAYO STORAGE\logo2.png"); Logo.ScaleAbsolute(160, 70); Logo.SetAbsolutePosition(70, 760); Pcb.AddImage(Logo); // Top Heading Pcb.SetTextMatrix(485, 790); Pcb.SetFontAndSize(f_times, 16); Pcb.ShowText("INVOICE"); Pcb.SetFontAndSize(f_times, 12); Pcb.ShowTextAligned(2, "INVOICE #: " + STD.Id.ToString(), 160, 735, 0);// here we will enter the pCode for this student Pcb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "MAILING", 155, 705, 0); Pcb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "INFO", 155, 693, 0); Pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "17 HOLDENGARDE AVE", 165, 705, 0); Pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "HILSIDE", 165, 690, 0); Pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BULAWAYO", 165, 675, 0); Pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "+263 (77) 228 2579", 165, 660, 0); Pcb.SetFontAndSize(f_times, 16); Pcb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "DESCRIPTION", 180, 625, 0); Pcb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "AMOUNT", 495, 625, 0); Pcb.EndText(); }
public static void GeneratePODForm(string templateFormsPath, string podFilePath, string receivedBy, string receivingTime, string signature) { PdfReader reader = new PdfReader(templateFormsPath); //select three pages from the original document reader.SelectPages("1-3"); //create PdfStamper object to write to get the pages from reader PdfStamper stamper = new PdfStamper(reader, new FileStream(podFilePath, FileMode.Create)); Rectangle pagesize = reader.GetPageSize(1); // PdfContentByte from stamper to add content to the pages over the original content PdfContentByte pbover = stamper.GetOverContent(1); PdfContentByte pbunder = stamper.GetUnderContent(1); //add content to the page using ColumnText ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(receivedBy), pagesize.Left + 320, pagesize.Bottom + 90, 0); ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(receivingTime), pagesize.Left + 400, pagesize.Bottom + 60, 0); // PdfContentByte from stamper to add content to the pages under the original content //add image from a file iTextSharp.text.Image img = new Jpeg(imageToByteArray(System.Drawing.Image.FromFile(signature))); //add the image under the original content img.SetAbsolutePosition(pagesize.Left + 380, pagesize.Bottom + 10); pbunder.AddImage(img); //pbunder.AddImage(img, img.Width / 2, 0, 0, img.Height / 2, 0, 0); //close the stamper stamper.Close(); }
private void ImagemRodape(PdfWriter writer, int numberPage) { BaseFont f_tr = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte canvas = writer.DirectContent; //Classe do ItextSharp para instânciar uma imagem Image image1 = Image.GetInstance("..\\..\\Imagens\\imagem1.png"); image1.SetAbsolutePosition(40, 1); //Horizontal, vertical image1.ScaleAbsoluteHeight(60); image1.ScaleAbsoluteWidth(60); canvas.AddImage(image1); //Linha canvas.MoveTo(40, 60); canvas.LineTo(575, 60); canvas.SetLineWidth(2); canvas.Stroke(); //Rodapé PdfTemplate tmpFooter = canvas.CreateTemplate(540, 70); canvas.AddTemplate(tmpFooter, 50, 1); tmpFooter.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, false), 5); tmpFooter.BeginText(); tmpFooter.SetFontAndSize(f_tr, 8); tmpFooter.ShowTextAligned(1, "TextoTextoTextoTextoTextoTextoTextoTexto", 240, 30, 0); tmpFooter.ShowTextAligned(2, string.Format("Página {0}", numberPage), 520, 10, 0); tmpFooter.EndText(); }
protected void AddPageNumberAndLogo(string url) { byte[] bytes = File.ReadAllBytes(url); AcroFields pdfFormFields; string imagenTanner = "LogoTCB.PNG"; string imagenPath = Path.Combine(@"img/", imagenTanner); Font blackFont = FontFactory.GetFont("Arial", 20.5f, Font.NORMAL, BaseColor.BLACK); using (MemoryStream stream = new MemoryStream()) { PdfReader reader = new PdfReader(bytes); using (PdfStamper stamper = new PdfStamper(reader, stream)) { pdfFormFields = stamper.AcroFields; int pages = reader.NumberOfPages; for (int i = 1; i <= pages; i++) { ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_CENTER, new Phrase("Pagina " + i.ToString() + " de " + pages, blackFont), 230f, 15f, 0); Image instanceImg = Image.GetInstance(imagenPath); instanceImg.ScalePercent(12); PdfContentByte overContent = stamper.GetOverContent(i); instanceImg.SetAbsolutePosition(3160f, 2295f); instanceImg.Alignment = Image.ALIGN_RIGHT; overContent.AddImage(instanceImg); } } bytes = stream.ToArray(); } File.WriteAllBytes(url, bytes); }
// --------------------------------------------------------------------------- /** * Draws the image of the month to the calendar. * @param canvas the direct content layer * @param dt the DateTime (to know which picture to use) */ public void DrawImageAndText(PdfContentByte canvas, DateTime dt) { string MM = dt.ToString("MM"); // get the image Image img = Image.GetInstance(Path.Combine( RESOURCE, MM + ".jpg" )); img.ScaleToFit(PageSize.A4.Height, PageSize.A4.Width); img.SetAbsolutePosition( (PageSize.A4.Height - img.ScaledWidth) / 2, (PageSize.A4.Width - img.ScaledHeight) / 2 ); canvas.AddImage(img); // add metadata canvas.SaveState(); canvas.SetCMYKColorFill(0x00, 0x00, 0x00, 0x80); Phrase p = new Phrase(string.Format( "{0} - \u00a9 Katharine Osborne", content[string.Format("{0}.jpg", dt.ToString("MM"))] ), small ); ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, p, 5, 5, 0); p = new Phrase( "Calendar generated using iText - example for the book iText in Action 2nd Edition", small ); ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT, p, 839, 5, 0); canvas.RestoreState(); }
static void manipulatePdf(string src, string dest, string imageFile) { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create, FileAccess.Write)); //GetInstance(System.Drawing.Image image, BaseColor color, bool forceBW) { System.Drawing.Image img = System.Drawing.Image.FromFile(imageFile); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(img, iTextSharp.text.BaseColor.WHITE, false); PdfImage stream = new PdfImage(image, "", null); stream.Put(new PdfName("ITXT_SpecialId"), new PdfName("123456789")); PdfIndirectObject reference = stamper.Writer.AddToBody(stream); image.DirectReference = reference.IndirectReference; image.ScaleAbsolute(133, 100); iTextSharp.text.Rectangle pagesize = reader.GetPageSizeWithRotation(1); image.SetAbsolutePosition(0, pagesize.Height - 100); //image.ScaleAbsolute(new iTextSharp.text.Rectangle( PdfContentByte over = stamper.GetOverContent(1); over.AddImage(image); stamper.Close(); reader.Close(); }
public void OnStartPage(PdfWriter writer, Document document) { float fontSize = 80; float xPosition = 300; float yPosition = 400; float angle = 45; try { PdfContentByte under = writer.DirectContentUnder; BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\CAMBRIAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); under.BeginText(); under.SetColorFill(BaseColor.LIGHT_GRAY); under.SetFontAndSize(baseFont, fontSize); under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle); under.EndText(); if (watermarkImage != null) { under.AddImage(watermarkImage); } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } }
private void CreateBorder(PdfContentByte cb, PdfWriter writer, Document doc) { iTextSharp.text.Rectangle r = doc.PageSize; float left = r.Left + 30; float right = r.Right - 30; float top = r.Top - 30; float bottom = r.Bottom + 30; float width = right - left; float height = top - bottom; PdfPTable tab = new PdfPTable(1); tab.TotalWidth = width; tab.LockedWidth = true; PdfPCell t = new PdfPCell(new Phrase(String.Empty)); t.BackgroundColor = new BaseColor(250, 235, 215); t.FixedHeight = height; t.BorderWidth = 3; tab.AddCell(t); Paragraph pa = new Paragraph(); pa.Add(tab); float h = tab.TotalHeight; PdfTemplate temp = cb.CreateTemplate(tab.TotalWidth, h); tab.WriteSelectedRows(0, -1, 0.0F, h, temp); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(temp); img.SetAbsolutePosition(30, 30); cb.AddImage(img); }
private void buttonStampa_Click(object sender, EventArgs e) { FindAndKillProcess("Acrobat"); FindAndKillProcess("AcroRd32"); PdfReader pdfReader = new PdfReader(@"vuota.pdf"); Rectangle size = pdfReader.GetPageSize(1); using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(@"barcode.pdf", FileMode.Create))) { foreach (var p in pagine.Select((obj, i) => new { Index = i, Lista = obj })) { var indice = p.Index; var pagina = p.Lista; if (indice > 0) { pdfStamper.InsertPage(indice + 1, size); } PdfContentByte cb = pdfStamper.GetUnderContent(indice + 1); foreach (var cf in pagina) { cb.AddImage(creaCodiceBarre(cb, cf, pagina.IndexOf(cf))); } } pdfStamper.Close(); } Process.Start(@"barcode.pdf"); }
private void RenderLogo() { cb = writer.DirectContent; iTextSharp.text.Image Logo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath(this.LogoImagePath)); //Logo.ScaleToFit(200, 43); Logo.SetAbsolutePosition(15, 470); cb.AddImage(Logo); }
private static void CreateHeaderFooter(PdfContentByte cb) { var path = "C:\\Users\\sMOOT\\source\\repos\\ResilienceAssessmentSystem\\ResilienceReporting\\Images\\footer.png"; var img = Image.GetInstance(path); img.SetAbsolutePosition(0, 0); img.ScaleAbsoluteWidth(PageSize.A4.Width); img.ScaleAbsoluteHeight(70); cb.AddImage(img, false); path = "C:\\Users\\sMOOT\\source\\repos\\ResilienceAssessmentSystem\\ResilienceReporting\\Images\\header.png"; img = Image.GetInstance(path); img.SetAbsolutePosition(0, PageSize.A4.Top - mm(35)); img.ScaleAbsoluteWidth(PageSize.A4.Width); img.ScaleAbsoluteHeight(mm(35)); cb.AddImage(img, false); }
private void RenderLogo() { cb = writer.DirectContent; iTextSharp.text.Image Logo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath(ImagePath)); Logo.ScaleToFit(200, 83); Logo.SetAbsolutePosition(35, PageHeight - 90); cb.AddImage(Logo); }
protected override void AddWatermark(PdfContentByte content) { Image image = Image.GetInstance(_imagePath); image.SetAbsolutePosition(_position.X, _position.Y); content.AddImage(image); }
protected void AddDataTableToPDF() { string taskid = HttpContext.Current.Session["Name"].ToString(); HttpContext.Current.Session.Timeout = 60; String pathin = System.Web.HttpContext.Current.Server.MapPath("~/storepdf/" + taskid + ".pdf"); String pathout = System.Web.HttpContext.Current.Server.MapPath("~/editorpdf/" + taskid + ".pdf"); iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(pathin); PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)); int n = reader.NumberOfPages; string imageURL = System.Web.HttpContext.Current.Server.MapPath(".") + "/img/caslab.jpg"; iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageURL); img.SetAbsolutePosition(60f, 790f); for (var i = 1; i <= n; i++) { PdfContentByte over = null; over = stamper.GetOverContent(i); BaseFont bf_times = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, "Cp1252", false); over.SetFontAndSize(bf_times, 10); over.AddImage(img); over.BeginText(); over.ShowTextAligned(PdfContentByte.ALIGN_CENTER, taskid, 500, 800, 0); over.EndText(); over.BeginText(); string pagenumber = "Page " + i + " of " + n + ""; over.ShowTextAligned(1, pagenumber, 500, 790, 0); over.EndText(); over.BeginText(); string headerline = "_______________________________________________________________________________________"; // put the alignment and coordinates here over.ShowTextAligned(1, headerline, 295, 780, 0); over.EndText(); over.BeginText(); string footerline = "________________________________________________________________________________________"; // put the alignment and coordinates here over.ShowTextAligned(1, footerline, 295, 60, 0); over.EndText(); over.BeginText(); string footer = "This document and all the information contained here are confidential and exclusive property of CASLAB."; over.ShowTextAligned(PdfContentByte.ALIGN_CENTER, footer, 300, 40, 0); over.EndText(); over.BeginText(); string footer1 = "and maynot be reproduced,disclosed,or made public in any manner prior to express written authorization by CASLAB."; over.ShowTextAligned(PdfContentByte.ALIGN_CENTER, footer1, 300, 30, 0); over.EndText(); } stamper.Close(); reader.Close(); }
private void CreatePdfOverviewMap(PdfContentByte content, Configuration.PrintTemplateContentRow row) { AppState appState = new AppState(); appState.Application = _appState.Application; Configuration.ApplicationRow application = AppContext.GetConfiguration().Application.First(o => o.ApplicationID == appState.Application); appState.MapTab = application.OverviewMapID; appState.Extent = application.GetFullExtentEnvelope(); int pixelWidth = Convert.ToInt32(row.Width * PixelsPerInch); int pixelHeight = Convert.ToInt32(row.Height * PixelsPerInch); MapMaker mapMaker = new MapMaker(appState, pixelWidth, pixelHeight, 2); MapImageData mapImageData = mapMaker.GetImage(); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(new MemoryStream(mapImageData.Image)); Transformation trans = new AffineTransformation(pixelWidth * 2, pixelHeight * 2, appState.Extent); MapGraphics mapGraphics = MapGraphics.FromImage(bitmap, trans); double minSize = (trans.Transform(new Coordinate(1, 0)).X - trans.Transform(new Coordinate(0, 0)).X) * 12; Envelope extent = new Envelope(new Coordinate(_appState.Extent.MinX, _appState.Extent.MinY), new Coordinate(_appState.Extent.MaxX, _appState.Extent.MaxY)); if (extent.Width < minSize) { extent = new Envelope(new Coordinate(extent.Centre.X - minSize * 0.5, extent.MinY), new Coordinate(extent.Centre.X + minSize * 0.5, extent.MaxY)); } if (extent.Height < minSize) { extent = new Envelope(new Coordinate(extent.MinX, extent.Centre.Y - minSize * 0.5), new Coordinate(extent.MaxX, extent.Centre.Y + minSize * 0.5)); } System.Drawing.Brush brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(64, System.Drawing.Color.Red)); System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Red, 4); mapGraphics.FillEnvelope(brush, extent); mapGraphics.DrawEnvelope(pen, extent); MemoryStream stream = new MemoryStream(); bitmap.Save(stream, mapImageData.Type == CommonImageType.Png ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg); byte[] mapImage = stream.ToArray(); float originX = Convert.ToSingle(row.OriginX) * PointsPerInch; float originY = Convert.ToSingle(row.OriginY) * PointsPerInch; float width = Convert.ToSingle(row.Width) * PointsPerInch; float height = Convert.ToSingle(row.Height) * PointsPerInch; iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(mapImage); image.SetAbsolutePosition(originX, originY); image.ScaleAbsolute(width, height); content.AddImage(image); CreatePdfBox(content, row, false); }
public void CellLayout( PdfPCell cell, Rectangle rectangle, PdfContentByte[] pcb) { PdfContentByte cb = pcb[PdfPTable.BACKGROUNDCANVAS]; cb.AddImage(_background, rectangle.Width, 0, 0, rectangle.Height, rectangle.Left, rectangle.Bottom ); }
/// <summary> /// 根据数据填充模板并获取一个一个pdf文件流 /// </summary> /// <param name="listPara">数据参数</param> /// <returns>所有的pdf文件字节数组,并装在一个数组中</returns> public static List <byte[]> GetPdfs(List <Dictionary <string, string> > listPara) { //获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。 BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); List <byte[]> pdfStreams = new List <byte[]>(); foreach (Dictionary <string, string> para in listPara) { //读取模板文件 PdfReader reader = new PdfReader(@"C:\Users\Administrator\Desktop\template.pdf"); //创建文件流用来保存填充模板后的文件 MemoryStream stream = new MemoryStream(); PdfStamper stamp = new PdfStamper(reader, stream); stamp.AcroFields.AddSubstitutionFont(baseFont); AcroFields form = stamp.AcroFields; stamp.FormFlattening = true;//表单文本框锁定 //填充表单 foreach (KeyValuePair <string, string> parameter in para) { //要输入中文就要设置域的字体; form.SetFieldProperty(parameter.Key, "textfont", baseFont, null); //为需要赋值的域设置值; form.SetField(parameter.Key, parameter.Value); } //添加图片 // 通过域名获取所在页和坐标,左下角为起点 float[] positions = form.GetFieldPositions("sender"); int pageNo = (int)positions[0]; float x = positions[1]; float y = positions[2]; // 读图片 Image image = Image.GetInstance(@"C:\Users\Administrator\Desktop\02.png"); // 获取操作的页面 PdfContentByte under = stamp.GetOverContent(pageNo); // 根据域的大小缩放图片 image.ScaleToFit(positions[3] - positions[1], positions[4] - positions[2]); // 添加图片 image.SetAbsolutePosition(x, y); under.AddImage(image); stamp.Close(); reader.Close(); byte[] result = stream.ToArray(); pdfStreams.Add(result); } return(pdfStreams); }
protected virtual void DrawLogo(PdfWriter writer, Document document) { // TO DO if (_settings.Logo.IsNotNull()) { _settings.Logo.SetAbsolutePosition(_settings.PageSize.Width - 50, _settings.PageSize.Height / 4); _pdfContentByte.AddImage(_settings.Logo); } }
static void add_image(PdfContentByte pcb, System.Drawing.Image image, System.Drawing.Point point) { image = ImageRoutines.GetCroppedByColor(image, System.Drawing.Color.Transparent); Image i = Image.GetInstance(image, (BaseColor)null); var ratio = Math.Min((float)SignatureMaxSize.Width / image.Width, (float)SignatureMaxSize.Height / image.Height); i.ScalePercent(ratio * 100); i.SetAbsolutePosition(point.X, point.Y); pcb.AddImage(i); }
private void AddQRCode(PdfContentByte ContentByte, string msg, float x, float y, int Margin = 5) { BarcodeQRCode qrcode = new BarcodeQRCode(msg, 1, 1, null); Image image = qrcode.GetImage(); x = x - (image.Width + Margin); y = y + Margin; image.SetAbsolutePosition(x, y); ContentByte.AddImage(image); }
/** * Writes a text line to the document. It takes care of all the attributes. * <P> * Before entering the line position must have been established and the * <CODE>text</CODE> argument must be in text object scope (<CODE>beginText()</CODE>). * @param line the line to be written * @param text the <CODE>PdfContentByte</CODE> where the text will be written to * @param graphics the <CODE>PdfContentByte</CODE> where the graphics will be written to * @param currentValues the current font and extra spacing values * @param ratio * @throws DocumentException on error */ internal void WriteLineToContent(PdfLine line, PdfContentByte text, PdfContentByte graphics, Object[] currentValues, float ratio) { PdfFont currentFont = (PdfFont)(currentValues[0]); float lastBaseFactor = (float)currentValues[1]; //PdfChunk chunkz; int numberOfSpaces; int lineLen; bool isJustified; float hangingCorrection = 0; float hScale = 1; float lastHScale = float.NaN; float baseWordSpacing = 0; float baseCharacterSpacing = 0; float glueWidth = 0; numberOfSpaces = line.NumberOfSpaces; lineLen = line.GetLineLengthUtf32(); // does the line need to be justified? isJustified = line.HasToBeJustified() && (numberOfSpaces != 0 || lineLen > 1); int separatorCount = line.GetSeparatorCount(); if (separatorCount > 0) { glueWidth = line.WidthLeft / separatorCount; } else if (isJustified) { if (line.NewlineSplit && line.WidthLeft >= (lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1))) { if (line.RTL) { text.MoveText(line.WidthLeft - lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1), 0); } baseWordSpacing = ratio * lastBaseFactor; baseCharacterSpacing = lastBaseFactor; } else { float width = line.WidthLeft; PdfChunk last = line.GetChunk(line.Size - 1); if (last != null) { String s = last.ToString(); char c; if (s.Length > 0 && hangingPunctuation.IndexOf((c = s[s.Length - 1])) >= 0) { float oldWidth = width; width += last.Font.Width(c) * 0.4f; hangingCorrection = width - oldWidth; } } float baseFactor = width / (ratio * numberOfSpaces + lineLen - 1); baseWordSpacing = ratio * baseFactor; baseCharacterSpacing = baseFactor; lastBaseFactor = baseFactor; } } int lastChunkStroke = line.LastStrokeChunk; int chunkStrokeIdx = 0; float xMarker = text.XTLM; float baseXMarker = xMarker; float yMarker = text.YTLM; bool adjustMatrix = false; float tabPosition = 0; // looping over all the chunks in 1 line foreach (PdfChunk chunk in line) { Color color = chunk.Color; hScale = 1; if (chunkStrokeIdx <= lastChunkStroke) { float width; if (isJustified) { width = chunk.GetWidthCorrected(baseCharacterSpacing, baseWordSpacing); } else { width = chunk.Width; } if (chunk.IsStroked()) { PdfChunk nextChunk = line.GetChunk(chunkStrokeIdx + 1); if (chunk.IsSeparator()) { width = glueWidth; Object[] sep = (Object[])chunk.GetAttribute(Chunk.SEPARATOR); IDrawInterface di = (IDrawInterface)sep[0]; bool vertical = (bool)sep[1]; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); if (vertical) { di.Draw(graphics, baseXMarker, yMarker + descender, baseXMarker + line.OriginalWidth, ascender - descender, yMarker); } else { di.Draw(graphics, xMarker, yMarker + descender, xMarker + width, ascender - descender, yMarker); } } if (chunk.IsTab()) { Object[] tab = (Object[])chunk.GetAttribute(Chunk.TAB); IDrawInterface di = (IDrawInterface)tab[0]; tabPosition = (float)tab[1] + (float)tab[3]; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); if (tabPosition > xMarker) { di.Draw(graphics, xMarker, yMarker + descender, tabPosition, ascender - descender, yMarker); } float tmp = xMarker; xMarker = tabPosition; tabPosition = tmp; } if (chunk.IsAttribute(Chunk.BACKGROUND)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.BACKGROUND)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); Object[] bgr = (Object[])chunk.GetAttribute(Chunk.BACKGROUND); graphics.SetColorFill((Color)bgr[0]); float[] extra = (float[])bgr[1]; graphics.Rectangle(xMarker - extra[0], yMarker + descender - extra[1] + chunk.TextRise, width - subtract + extra[0] + extra[2], ascender - descender + extra[1] + extra[3]); graphics.Fill(); graphics.SetGrayFill(0); } if (chunk.IsAttribute(Chunk.UNDERLINE)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.UNDERLINE)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object[][] unders = (Object[][])chunk.GetAttribute(Chunk.UNDERLINE); Color scolor = null; for (int k = 0; k < unders.Length; ++k) { Object[] obj = unders[k]; scolor = (Color)obj[0]; float[] ps = (float[])obj[1]; if (scolor == null) scolor = color; if (scolor != null) graphics.SetColorStroke(scolor); float fsize = chunk.Font.Size; graphics.SetLineWidth(ps[0] + fsize * ps[1]); float shift = ps[2] + fsize * ps[3]; int cap2 = (int)ps[4]; if (cap2 != 0) graphics.SetLineCap(cap2); graphics.MoveTo(xMarker, yMarker + shift); graphics.LineTo(xMarker + width - subtract, yMarker + shift); graphics.Stroke(); if (scolor != null) graphics.ResetGrayStroke(); if (cap2 != 0) graphics.SetLineCap(0); } graphics.SetLineWidth(1); } if (chunk.IsAttribute(Chunk.ACTION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.ACTION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; text.AddAnnotation(new PdfAnnotation(writer, xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size, (PdfAction)chunk.GetAttribute(Chunk.ACTION))); } if (chunk.IsAttribute(Chunk.REMOTEGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.REMOTEGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object[] obj = (Object[])chunk.GetAttribute(Chunk.REMOTEGOTO); String filename = (String)obj[0]; if (obj[1] is String) RemoteGoto(filename, (String)obj[1], xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); else RemoteGoto(filename, (int)obj[1], xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); } if (chunk.IsAttribute(Chunk.LOCALGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; LocalGoto((String)chunk.GetAttribute(Chunk.LOCALGOTO), xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); } if (chunk.IsAttribute(Chunk.LOCALDESTINATION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALDESTINATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; LocalDestination((String)chunk.GetAttribute(Chunk.LOCALDESTINATION), new PdfDestination(PdfDestination.XYZ, xMarker, yMarker + chunk.Font.Size, 0)); } if (chunk.IsAttribute(Chunk.GENERICTAG)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.GENERICTAG)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Rectangle rect = new Rectangle(xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); IPdfPageEvent pev = writer.PageEvent; if (pev != null) pev.OnGenericTag(writer, this, rect, (String)chunk.GetAttribute(Chunk.GENERICTAG)); } if (chunk.IsAttribute(Chunk.PDFANNOTATION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.PDFANNOTATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); PdfAnnotation annot = PdfFormField.ShallowDuplicate((PdfAnnotation)chunk.GetAttribute(Chunk.PDFANNOTATION)); annot.Put(PdfName.RECT, new PdfRectangle(xMarker, yMarker + descender, xMarker + width - subtract, yMarker + ascender)); text.AddAnnotation(annot); } float[] paramsx = (float[])chunk.GetAttribute(Chunk.SKEW); object hs = chunk.GetAttribute(Chunk.HSCALE); if (paramsx != null || hs != null) { float b = 0, c = 0; if (paramsx != null) { b = paramsx[0]; c = paramsx[1]; } if (hs != null) hScale = (float)hs; text.SetTextMatrix(hScale, b, c, 1, xMarker, yMarker); } if (chunk.IsImage()) { Image image = chunk.Image; float[] matrix = image.Matrix; matrix[Image.CX] = xMarker + chunk.ImageOffsetX - matrix[Image.CX]; matrix[Image.CY] = yMarker + chunk.ImageOffsetY - matrix[Image.CY]; graphics.AddImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); text.MoveText(xMarker + lastBaseFactor + image.ScaledWidth - text.XTLM, 0); } } xMarker += width; ++chunkStrokeIdx; } if (chunk.Font.CompareTo(currentFont) != 0) { currentFont = chunk.Font; text.SetFontAndSize(currentFont.Font, currentFont.Size); } float rise = 0; Object[] textRender = (Object[])chunk.GetAttribute(Chunk.TEXTRENDERMODE); int tr = 0; float strokeWidth = 1; Color strokeColor = null; object fr = chunk.GetAttribute(Chunk.SUBSUPSCRIPT); if (textRender != null) { tr = (int)textRender[0] & 3; if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.SetTextRenderingMode(tr); if (tr == PdfContentByte.TEXT_RENDER_MODE_STROKE || tr == PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE) { strokeWidth = (float)textRender[1]; if (strokeWidth != 1) text.SetLineWidth(strokeWidth); strokeColor = (Color)textRender[2]; if (strokeColor == null) strokeColor = color; if (strokeColor != null) text.SetColorStroke(strokeColor); } } if (fr != null) rise = (float)fr; if (color != null) text.SetColorFill(color); if (rise != 0) text.SetTextRise(rise); if (chunk.IsImage()) { adjustMatrix = true; } else if (chunk.IsHorizontalSeparator()) { PdfTextArray array = new PdfTextArray(); array.Add(-glueWidth * 1000f / chunk.Font.Size / hScale); text.ShowText(array); } else if (chunk.IsTab()) { PdfTextArray array = new PdfTextArray(); array.Add((tabPosition - xMarker) * 1000f / chunk.Font.Size / hScale); text.ShowText(array); } // If it is a CJK chunk or Unicode TTF we will have to simulate the // space adjustment. else if (isJustified && numberOfSpaces > 0 && chunk.IsSpecialEncoding()) { if (hScale != lastHScale) { lastHScale = hScale; text.SetWordSpacing(baseWordSpacing / hScale); text.SetCharacterSpacing(baseCharacterSpacing / hScale); } String s = chunk.ToString(); int idx = s.IndexOf(' '); if (idx < 0) text.ShowText(s); else { float spaceCorrection = - baseWordSpacing * 1000f / chunk.Font.Size / hScale; PdfTextArray textArray = new PdfTextArray(s.Substring(0, idx)); int lastIdx = idx; while ((idx = s.IndexOf(' ', lastIdx + 1)) >= 0) { textArray.Add(spaceCorrection); textArray.Add(s.Substring(lastIdx, idx - lastIdx)); lastIdx = idx; } textArray.Add(spaceCorrection); textArray.Add(s.Substring(lastIdx)); text.ShowText(textArray); } } else { if (isJustified && hScale != lastHScale) { lastHScale = hScale; text.SetWordSpacing(baseWordSpacing / hScale); text.SetCharacterSpacing(baseCharacterSpacing / hScale); } text.ShowText(chunk.ToString()); } if (rise != 0) text.SetTextRise(0); if (color != null) text.ResetRGBColorFill(); if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); if (strokeColor != null) text.ResetRGBColorStroke(); if (strokeWidth != 1) text.SetLineWidth(1); if (chunk.IsAttribute(Chunk.SKEW) || chunk.IsAttribute(Chunk.HSCALE)) { adjustMatrix = true; text.SetTextMatrix(xMarker, yMarker); } } if (isJustified) { text.SetWordSpacing(0); text.SetCharacterSpacing(0); if (line.NewlineSplit) lastBaseFactor = 0; } if (adjustMatrix) text.MoveText(baseXMarker - text.XTLM, 0); currentValues[0] = currentFont; currentValues[1] = lastBaseFactor; }