public bool WatermarkPDF_SN(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg) { try { PdfReader reader = new PdfReader(SourcePdfPath); PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create)); int n = reader.NumberOfPages; int i = 0; PdfContentByte under; iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath); im.SetAbsolutePosition(positionX, positionY); im.ScaleAbsolute(WatermarkWidth, WatermarkHeight); while (i < n) { i++; under = stamp.GetUnderContent(i); under.AddImage(im, true); } stamp.Close(); reader.Close(); } catch (Exception ex) { msg = ex.Message; return(false); } msg = "加水印成功!"; return(true); }
private byte[] FillForm(List <KeyValuePair <string, string> > templateData) { using (MemoryStream memoryStream = new MemoryStream()) { var pdfStamper = new PdfStamper(new PdfReader(_templatePath), memoryStream, '7'); var acroFields = pdfStamper.AcroFields; foreach (var parametro in templateData) { acroFields.SetField(parametro.Key, parametro.Value); } if (_images.Any()) { foreach (ImageData imagen in _images) { iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(imagen.Image, iTextSharp.text.BaseColor.White); pdfStamper.GetOverContent(1).AddImage(instance, instance.Width, 0, 0, instance.Height, imagen.HorizontalPosition, imagen.VerticalPosition - 10); } } pdfStamper.FormFlattening = true; pdfStamper.Close(); return(memoryStream.ToArray()); } }
public bool WatermarkPDF_SW(string SourcePdfPath, string OutputPdfPath, string WatermarkImageUrl, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg) { try { PdfReader reader = new PdfReader(SourcePdfPath); PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create)); int n = reader.NumberOfPages; int i = 0; PdfContentByte under; WatermarkWidth = WatermarkWidth / n; //这个地方要注意,是根据页数来动态加载图片地址,有几页就加载几页的图片 string WatermarkPath = Server.MapPath(Request.ApplicationPath + "/HTProject/Pages/Images/合同备案公章" + n + "/"); string WatermarkPath2 = ""; while (i < n) { i++; WatermarkPath2 = WatermarkPath + i + ".gif"; iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath2); im.SetAbsolutePosition(positionX, positionY); im.ScaleAbsolute(WatermarkWidth, WatermarkHeight); under = stamp.GetUnderContent(i); under.AddImage(im, true); } stamp.Close(); reader.Close(); } catch (Exception ex) { msg = ex.Message; return(false); } msg = "加水印成功!"; return(true); }
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(); }
void ConvertJPG2PDF(string jpgfile, string pdf) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); using (Stream stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)) { PdfWriter.GetInstance(document, stream); document.Open(); using (FileStream imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); } document.Close(); } }
public void Save(System.Drawing.Bitmap bm, string filename, System.Drawing.RotateFlipType rotate) { Bitmap image = bm; if (rotate != RotateFlipType.RotateNoneFlipNone) { image.RotateFlip(rotate); } using (FileStream stream = new FileStream(filename, FileMode.Create)) { using (iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN)) { iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream); pdfDocument.Open(); MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms); img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN)); pdfDocument.Add(img); pdfDocument.Close(); writer.Close(); } } }
protected iTextSharp.text.pdf.PdfPCell ImageCell(string path, float scale, int align, int rowSpan, int colSpan) { iTextSharp.text.pdf.PdfPCell cellImg = null; try { if (path != null) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(GetImagePath(path));//HttpContext.Current.Server.MapPath(path) image.ScalePercent(scale); cellImg = new iTextSharp.text.pdf.PdfPCell(image); cellImg.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP; // cellImg.BorderColor = iTextSharp.text.Color.WHITE; cellImg.HorizontalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_CENTER; cellImg.FixedHeight = 40f; cellImg.PaddingBottom = 0f; cellImg.PaddingTop = 1f; // cellImg.Top = 2f; if (rowSpan > 0) { cellImg.Rowspan = rowSpan; } if (colSpan > 0) { cellImg.Colspan = colSpan; } } } catch (Exception ex) { } return(cellImg); }
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); } }
private static void RotationPNG(iTextSharp.text.Image PNG) { if (PNG.Width > PNG.Height) { PNG.RotationDegrees = 90; } }
private byte[] ConvertJPG2PDF(Stream imageStream) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); MemoryStream memStream = new MemoryStream(); PdfWriter wr = PdfWriter.GetInstance(document, memStream); document.Open(); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); document.Close(); return(memStream.ToArray()); }
/// <summary> /// Scales the pdf image if nessarry by percent. /// </summary> /// <param name="img">The img.</param> /// <param name="frame">The frame.</param> /// <returns>The scaled image.</returns> private iTextSharp.text.Image ScaleIfNessarry(iTextSharp.text.Image img, Frame frame) { try { double scalingPrescision = 0.25; double scaledWidthPercent = 0; double scaledHeightPercent = 0; double odfScaledWidth = AODL.Document.Helper.SizeConverter.GetDoubleFromAnOfficeSizeValue(frame.SvgWidth); double odfScaledHeight = AODL.Document.Helper.SizeConverter.GetDoubleFromAnOfficeSizeValue(frame.SvgHeight); if ((frame.Height - odfScaledHeight) > scalingPrescision || (frame.Height - odfScaledHeight) < scalingPrescision) { scaledHeightPercent = ((100.0 / frame.Height) * odfScaledHeight); Console.WriteLine("ScaledHeightPerc {0} , frame {1}, odfScaledHeight {2}", scaledHeightPercent, frame.Height, odfScaledHeight); } if ((frame.Width - odfScaledWidth) > scalingPrescision || (frame.Width - odfScaledWidth) < scalingPrescision) { scaledWidthPercent = ((100.0 / frame.Width) * odfScaledWidth); } if (scaledHeightPercent != 0 || scaledWidthPercent != 0) { img.ScalePercent((float)scaledWidthPercent, (float)scaledHeightPercent); } return(img); } catch (Exception) { throw; } }
public void Sign(bool visible, string rutaImagen) { PdfReader reader = new PdfReader(this.inputPDF); //Activate MultiSignatures PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true); //To disable Multi signatures uncomment this line : every new signature will invalidate older ones ! //PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0'); st.MoreInfo = this.metadata.getMetaData(); st.XmpMetadata = this.metadata.getStreamedMetaData(); PdfSignatureAppearance sap; sap = st.SignatureAppearance; sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED); //string img = "C:\Users\USUARIO\Desktop\darth.png"; string imagePath = rutaImagen; iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(imagePath); sap.Reason = "FIRMA ELECTRÓNICA"; sap.Image = imagen; sap.Location = "PERÚ"; if (visible) { sap.SetVisibleSignature(new iTextSharp.text.Rectangle(480, 10, 600, 60), 1, null); } st.Close(); }
public static void CreatePDF(Image image, string filePath, ImageFormat format) { string directoryPath = Path.GetDirectoryName(filePath); string filename = Path.GetFileNameWithoutExtension(filePath); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); try { var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(Path.Combine(directoryPath, filename) + ".pdf", FileMode.Create)); document.Open(); iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, format); iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(); pic.Border = 1; pic.BorderColor = iTextSharp.text.BaseColor.BLACK; paragraph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; paragraph.Add(pic); document.Add(paragraph); document.NewPage(); } catch (iTextSharp.text.DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } document.Close(); }
public static string SavePDF(string strInputFile, string strOutputFile) { iTextSharp.text.Document doc = null; try { iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(strInputFile); iTextSharp.text.Rectangle rectDocSize = new iTextSharp.text.Rectangle(img.Width, img.Height); doc = new iTextSharp.text.Document(rectDocSize); iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(strOutputFile, FileMode.Create)); doc.Open(); //doc.Add(new iTextSharp.text.Paragraph("GIF")); doc.Add(img); } catch (iTextSharp.text.DocumentException dex) { throw dex; } catch (IOException ioex) { throw ioex; } catch (Exception ex) { throw ex; } finally { if (doc != null) { doc.Close(); } } return(strOutputFile); }
public static void AddPic(iTextSharp.text.Document document, string imagefile, int chartid, Canvas canvas) { ImageFromPieControl(imagefile, chartid, canvas); iTextSharp.text.Image pdfimage = iTextSharp.text.Image.GetInstance(imagefile); pdfimage.SetDpi(300, 300); float left = 425; if (chartid == 2) { pdfimage.ScaleAbsolute(120, 120 * (550f / 350f)); left = 440; } else { pdfimage.ScaleToFit(140, 140); } float y = 0; switch (chartid) { case 0: y = 600; break; case 1: y = 365; break; case 2: y = 45; break; } pdfimage.SetAbsolutePosition(left, y); document.Add(pdfimage); }
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(); }
private void button2_Click(object sender, EventArgs e) { if (textBox1.Text.Trim() != string.Empty) { iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0); // creation of the different writers iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\temp\Converted.pdf", System.IO.FileMode.Create)); // load the tiff image and count the total pages System.Drawing.Bitmap bm = new System.Drawing.Bitmap(this.openFileDialog1.FileName); int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); document.Open(); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; for (int k = 0; k < total; ++k) { bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Tiff); img.SetAbsolutePosition(0, 0); img.ScaleAbsoluteHeight(document.PageSize.Height); img.ScaleAbsoluteWidth(document.PageSize.Width); cb.AddImage(img); document.NewPage(); } document.Close(); axAcroPDF1.LoadFile(@"C:\temp\Converted.pdf"); } }
protected iTextSharp.text.pdf.PdfPCell ImageCell(string path, float scale, float height, int hAlign, int vAlign = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP, float p_left = 0f, float p_right = 0f, float p_top = 0f, float p_btm = 0f, string borderPattren = "T,R,B") { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(GetImagePath(path));//HttpContext.Current.Server.MapPath(path) image.ScalePercent(scale); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image); cell.BorderColor = iTextSharp.text.Color.BLACK; cell.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP; cell.HorizontalAlignment = hAlign; //cell.PaddingBottom = 0f; //cell.PaddingTop = 0f; cell.Border = GetBorderSides(borderPattren); if (p_btm >= 0f) { cell.PaddingBottom = p_btm; } if (p_top >= 0f) { cell.PaddingTop = p_top; } if (p_left >= 0f) { cell.PaddingLeft = p_left; } if (p_right >= 0f) { cell.PaddingRight = p_right; } return(cell); }
/* (non-Javadoc) * @see com.itextpdf.tool.xml.css.CssApplier#apply(com.itextpdf.text.Element, com.itextpdf.tool.xml.Tag) */ virtual public Image Apply(Image img, Tag tag) { String widthValue; tag.CSS.TryGetValue(HTML.Attribute.WIDTH, out widthValue); if (widthValue == null) { tag.Attributes.TryGetValue(HTML.Attribute.WIDTH, out widthValue); } String heightValue; tag.CSS.TryGetValue(HTML.Attribute.HEIGHT, out heightValue); if (heightValue == null) { tag.Attributes.TryGetValue(HTML.Attribute.HEIGHT, out heightValue); } if (widthValue == null) img.ScaleToFitLineWhenOverflow = true; else img.ScaleToFitLineWhenOverflow = false; if (heightValue == null) img.ScaleToFitHeight = true; else img.ScaleToFitHeight = false; CssUtils utils = CssUtils.GetInstance(); float widthInPoints = utils.ParsePxInCmMmPcToPt(widthValue); float heightInPoints = utils.ParsePxInCmMmPcToPt(heightValue); if (widthInPoints > 0 && heightInPoints > 0) { img.ScaleAbsolute(widthInPoints, heightInPoints); } else if (widthInPoints > 0) { heightInPoints = img.Height * widthInPoints / img.Width; img.ScaleAbsolute(widthInPoints, heightInPoints); } else if (heightInPoints > 0) { widthInPoints = img.Width * heightInPoints / img.Height; img.ScaleAbsolute(widthInPoints, heightInPoints); } String before; tag.CSS.TryGetValue(CSS.Property.BEFORE, out before); if (before != null) { img.SpacingBefore = float.Parse(before, CultureInfo.InvariantCulture); } String after; tag.CSS.TryGetValue(CSS.Property.AFTER, out after); if (after != null) { img.SpacingAfter = float.Parse(after, CultureInfo.InvariantCulture); } img.WidthPercentage = 0; return img; }
public bool WatermarkPDF(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg, int ryCount) { try { PdfReader reader = new PdfReader(SourcePdfPath); PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create)); int n = reader.NumberOfPages; int i = 0; PdfContentByte under; while (i < n) { i++; under = stamp.GetUnderContent(i); iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath); im.ScaleAbsolute(WatermarkWidth, WatermarkHeight); //im.SetAbsolutePosition(positionX, positionY); float height = 841; if (i == n) { string imgHYPath = Server.MapPath(Request.ApplicationPath + "/HTProject/Pages/Images/核验章.png"); iTextSharp.text.Image imHY = iTextSharp.text.Image.GetInstance(imgHYPath); imHY.ScaleAbsolute(100, 50); if (i == 1)//说明就一页 { height = height - 160 - ryCount * 23 - 115; //再加上已核验的章 imHY.SetAbsolutePosition(200, height + 35); } else { height = height - (ryCount - 18) * 23; //再加上已核验的章 imHY.SetAbsolutePosition(200, height + 35); } under.AddImage(imHY, true); im.SetAbsolutePosition(positionX, height); } else//不是第一页,也不是最后一页 { im.SetAbsolutePosition(positionX, positionY); } under.AddImage(im, true); } stamp.Close(); reader.Close(); } catch (Exception ex) { msg = ex.Message; return(false); } msg = "加水印成功!"; return(true); }
/// <summary> /// /// This method create the image on the base of the byte array /// </summary> /// <param name="data"></param> /// <returns></returns> public iTextSharp.text.Image GetImage(byte[] data) { image = iTextSharp.text.Image.GetInstance(byteArrayToImage1(data), System.Drawing.Imaging.ImageFormat.Jpeg); image.ScalePercent(200); return image; }
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 void button2_Click(object sender, EventArgs e) { CardGenerator generateUserCard = new CardGenerator(); string file = Application.ExecutablePath + "qr.jpg"; iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(file); image.ScaleToFit(120f, 120f); generateUserCard.GenerateCard(textBox1, textBox2, textBox3, image); }
private static iTextSharp.text.Image checkImage(this iTextSharp.text.Image img) { if (img == null) { throw new InvalidOperationException("iTextSharp.text.Image is null."); } return(img); }
public ActionResult GeneratePDFforFinancialPolicy(int?id) { Subject subject = db.SubjectDatabase.Find(id); //create new pdf form from template var reader = new PdfReader(Server.MapPath("~/Content/FinancialPolicy.pdf")); //var output = new MemoryStream(); var output = new FileStream(Server.MapPath("~/PDF_handler/FinancialPolicy.pdf"), FileMode.Create); var stamper = new PdfStamper(reader, output); //fill fiels on pdf form. stamper.AcroFields.SetField("PrintName", subject.Name); stamper.AcroFields.SetField("PrintName2", subject.Name); stamper.AcroFields.SetField("Date", DateTime.Now.ToShortDateString()); //put in signatures Signature signatureclient = (Signature)TempData["SignatureClientInsurance"]; if (signatureclient == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } //first signature Image x = (Bitmap)((new ImageConverter()).ConvertFrom(signatureclient.MySignature)); System.Drawing.Image img = x; img.Save(Server.MapPath("~/Content/signatureclient.png"), System.Drawing.Imaging.ImageFormat.Png); iTextSharp.text.Image sigImg = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/signatureclient.png")); // Scale image to fit sigImg.ScaleToFit(45, 45); // Set signature position on page sigImg.SetAbsolutePosition(100, 55); //x, y // Add signatures to desired page PdfContentByte over = stamper.GetOverContent(1); over.AddImage(sigImg); stamper.FormFlattening = true; stamper.Close(); reader.Close(); string path = "~/PDF_handler/FinancialPolicy.pdf"; string tag = "Financial_Policy"; string GroupingID = id.ToString(); //return View(); return(RedirectToAction("SavePDFtoDatabase", "PDFs", new { path = path, tag = tag, GroupingID = GroupingID })); }
protected iTextSharp.text.pdf.PdfPCell ImageCell(byte[] path, float scale, int hAlign, int vAlign = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP, iTextSharp.text.Color backColor = null) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path); image.ScalePercent(scale); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image); cell.BorderColor = backColor == null ? iTextSharp.text.Color.WHITE : backColor; cell.VerticalAlignment = vAlign; cell.HorizontalAlignment = hAlign; cell.PaddingBottom = 0f; cell.PaddingTop = 0f; return(cell); }
public PdfPCell ImageCell(string path, float scale, int align, iTextSharp.text.BaseColor CellBorderColer) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath(path)); image.ScalePercent(scale); PdfPCell cell = new PdfPCell(image); cell.BorderColor = CellBorderColer; cell.VerticalAlignment = PdfPCell.ALIGN_CENTER; cell.HorizontalAlignment = align; cell.PaddingBottom = 0f; cell.PaddingTop = 2f; return(cell); }
private iTextSharp.text.Table Obtener_Logos(System.Web.UI.Page pPage) { iTextSharp.text.Table tbLogos = null; iTextSharp.text.Cell tdCell = null; iTextSharp.text.Image oFinancieraUno = null; iTextSharp.text.Image oOechsle = null; // Tabla tbLogos = new iTextSharp.text.Table(3); tbLogos.Width = 90; tbLogos.Cellpadding = 1; tbLogos.Cellspacing = 0; tbLogos.Border = iTextSharp.text.Rectangle.NO_BORDER; // if (pPage == null) { oFinancieraUno = iTextSharp.text.Image.GetInstance(string.Concat(System.Web.Hosting.HostingEnvironment.MapPath("~/Imagen/"), "Logo_ESSolutions.jpg")); } else { oFinancieraUno = iTextSharp.text.Image.GetInstance(string.Concat(pPage.Server.MapPath("~/Imagen/"), "Logo_ESSolutions.jpg")); } oFinancieraUno.ScaleAbsolute(300, 90); tdCell = new iTextSharp.text.Cell(); tdCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; tdCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; tdCell.Border = iTextSharp.text.Rectangle.NO_BORDER; tdCell.Add(oFinancieraUno); tbLogos.AddCell(tdCell); // tdCell = new iTextSharp.text.Cell(String.Empty); tdCell.Border = iTextSharp.text.Rectangle.NO_BORDER; tbLogos.AddCell(tdCell); // if (pPage == null) { oOechsle = iTextSharp.text.Image.GetInstance(string.Concat(System.Web.Hosting.HostingEnvironment.MapPath("~/Imagen/"), "Logo_ESSolutions.jpg")); } else { oOechsle = iTextSharp.text.Image.GetInstance(string.Concat(pPage.Server.MapPath("~/Imagen/"), "Logo_ESSolutions.jpg")); } oOechsle.ScaleAbsolute(65, 45); tdCell = new iTextSharp.text.Cell(); tdCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; tdCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_TOP; tdCell.Border = iTextSharp.text.Rectangle.NO_BORDER; tdCell.Add(oOechsle); tbLogos.AddCell(tdCell); // return(tbLogos); }
public ActionResult GeneratePDFforSignature(int?id) { Signature signature = db.SignatureDatabase.Find(id); //this can be handled by converting the signature to jpg and saving locally in contents. //then accessing it when itextsharp needs it. then delete the stored local file before ending the function. Image x = (Bitmap)((new ImageConverter()).ConvertFrom(signature.MySignature)); System.Drawing.Image img = x; img.Save(Server.MapPath("~/Content/test1.png"), System.Drawing.Imaging.ImageFormat.Png); //debugging //img.Save(Server.MapPath("~/Content/test1.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg); //create new pdf form from template var reader = new PdfReader(Server.MapPath("~/Content/PDFforPersonalInformation.pdf")); var output = new MemoryStream(); var stamper = new PdfStamper(reader, output); iTextSharp.text.Image sigImg = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/test1.png")); // Scale image to fit sigImg.ScaleToFit(80, 80); // Set signature position on page sigImg.SetAbsolutePosition(170, 55); //x, y // Add signatures to desired page PdfContentByte over = stamper.GetOverContent(1); over.AddImage(sigImg); //close and create new pdf // Form fields should no longer be editable stamper.FormFlattening = true; stamper.Close(); reader.Close(); Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToShortDateString() + ".pdf"); Response.ContentType = "application/pdf"; Response.BinaryWrite(output.ToArray()); Response.End(); //delete signature image FileInfo file = new FileInfo(Server.MapPath("~/Content/test1.png")); file.Delete(); //return View(); return(RedirectToAction("Index")); }
public void SetImage(string fieldName, byte[] image) { if (image == null) { return; } float[] pos = stamper.AcroFields.GetFieldPositions(fieldName); for (int i = 0; i < pos.Length - 4; i += 5) { iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(image); img.ScaleToFit(Math.Abs(pos[i + 1] - pos[3]), Math.Abs(pos[i + 2] - pos[i + 4])); img.SetAbsolutePosition(pos[i + 1] + Math.Abs(pos[i + 1] - pos[i + 3]) / 2 - img.ScaledWidth / 2, pos[i + 2] + Math.Abs(pos[i + 2] - pos[i + 4]) / 2 - img.ScaledHeight / 2); stamper.GetOverContent((int)pos[i]).AddImage(img); } }
public static void CropImageToHeight(PdfImage img, float height) { if (img.Height <= height) { return; } float w = img.Width; float h = img.Height; float scaleFactor = height / h; w = w * scaleFactor; h = h * scaleFactor; img.ScaleAbsolute(w, h); }
protected iTextSharp.text.pdf.PdfPCell ImageCell(byte[] path, string SubHeading, string FontFamily, float fontSize = 10f, float scale = 50f, float Img_Height = 50f, float lbl_Height = 20f, int fontWeight = iTextSharp.text.Font.NORMAL, float totalWidth = 250f, float abWidth = 210, int rowSpan = 1, int colSpan = 1) { iTextSharp.text.pdf.PdfPTable tabSig = new iTextSharp.text.pdf.PdfPTable(1); iTextSharp.text.pdf.PdfPCell cell = null; try { tabSig.TotalWidth = totalWidth; tabSig.LockedWidth = true; tabSig.SetWidths(new float[] { 1.0f }); iTextSharp.text.pdf.PdfPCell cellSig = GetStringCell(SubHeading, FontFamily, fontSize, fontWeight, iTextSharp.text.Color.BLACK, iTextSharp.text.pdf.PdfCell.ALIGN_LEFT, iTextSharp.text.pdf.PdfCell.ALIGN_MIDDLE, lbl_Height, 5f, -1f, 4f, 4f, "", 1, 1); tabSig.AddCell(cellSig); if (path != null) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path); //image.ScaleAbsolute(220.0f,50.0f); //image.ScalePercent(scale); image.ScaleAbsolute(abWidth, scale); // image.ScalePercent(scale); iTextSharp.text.pdf.PdfPCell cellImg = new iTextSharp.text.pdf.PdfPCell(image); cellImg.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP; cellImg.BorderColor = iTextSharp.text.Color.WHITE; cellImg.HorizontalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_CENTER; cellImg.FixedHeight = Img_Height; cellImg.PaddingBottom = 0f; cellImg.PaddingTop = 1f; // cellImg.Top = 2f; tabSig.AddCell(cellImg); } cell = new iTextSharp.text.pdf.PdfPCell(tabSig); cell.BorderColor = iTextSharp.text.Color.BLACK; cell.HorizontalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_MIDDLE; cell.PaddingTop = 1f; cell.PaddingBottom = 1f; cell.Rowspan = rowSpan; cell.Colspan = colSpan; } catch (Exception ex) { } return(cell); }
/** * Applies CSS to an Image. Currently supported: * - width * - height * - borders (color, width) * - spacing before and after * * @param img the image * @param tag the tag with the css * @return a styled Image */ virtual public Image Apply(Image img, Tag tag) { IDictionary<String, String> cssMap = tag.CSS; String widthValue = null; cssMap.TryGetValue(HTML.Attribute.WIDTH, out widthValue); if (widthValue == null) { tag.Attributes.TryGetValue(HTML.Attribute.WIDTH, out widthValue); } String heightValue = null; cssMap.TryGetValue(HTML.Attribute.HEIGHT, out heightValue); if (heightValue == null) { tag.Attributes.TryGetValue(HTML.Attribute.HEIGHT, out heightValue); } if (widthValue == null) { img.ScaleToFitLineWhenOverflow = true; } else { img.ScaleToFitLineWhenOverflow = false; } img.ScaleToFitHeight = false; CssUtils utils = CssUtils.GetInstance(); float widthInPoints = utils.ParsePxInCmMmPcToPt(widthValue); float heightInPoints = utils.ParsePxInCmMmPcToPt(heightValue); if (widthInPoints > 0 && heightInPoints > 0) { img.ScaleAbsolute(widthInPoints, heightInPoints); } else if (widthInPoints > 0) { heightInPoints = img.Height * widthInPoints / img.Width; img.ScaleAbsolute(widthInPoints, heightInPoints); } else if (heightInPoints > 0) { widthInPoints = img.Width * heightInPoints / img.Height; img.ScaleAbsolute(widthInPoints, heightInPoints); } // apply border CSS String borderTopColor = null; cssMap.TryGetValue(CSS.Property.BORDER_TOP_COLOR, out borderTopColor); if (borderTopColor != null) { img.BorderColorTop = HtmlUtilities.DecodeColor(borderTopColor); } String borderTopWidth = null; cssMap.TryGetValue(CSS.Property.BORDER_TOP_WIDTH, out borderTopWidth); if (borderTopWidth != null) { img.BorderWidthTop = utils.ParseValueToPt(borderTopWidth, 1f); } String borderRightColor = null; cssMap.TryGetValue(CSS.Property.BORDER_RIGHT_COLOR, out borderRightColor); if (borderRightColor != null) { img.BorderColorRight = HtmlUtilities.DecodeColor(borderRightColor); } String borderRightWidth = null; cssMap.TryGetValue(CSS.Property.BORDER_RIGHT_WIDTH, out borderRightWidth); if (borderRightWidth != null) { img.BorderWidthRight = utils.ParseValueToPt(borderRightWidth, 1f); } String borderBottomColor = null; cssMap.TryGetValue(CSS.Property.BORDER_BOTTOM_COLOR, out borderBottomColor); if (borderBottomColor != null) { img.BorderColorBottom = HtmlUtilities.DecodeColor(borderBottomColor); } String borderBottomWidth = null; cssMap.TryGetValue(CSS.Property.BORDER_BOTTOM_WIDTH, out borderBottomWidth); if (borderBottomWidth != null) { img.BorderWidthBottom = utils.ParseValueToPt(borderBottomWidth, 1f); } String borderLeftColor = null; cssMap.TryGetValue(CSS.Property.BORDER_LEFT_COLOR, out borderLeftColor); if (borderLeftColor != null) { img.BorderColorLeft = HtmlUtilities.DecodeColor(borderLeftColor); } String borderLeftWidth = null; cssMap.TryGetValue(CSS.Property.BORDER_LEFT_WIDTH, out borderLeftWidth); if (borderLeftWidth != null) { img.BorderWidthLeft = utils.ParseValueToPt(borderLeftWidth, 1f); } // end of border CSS String before = null; cssMap.TryGetValue(CSS.Property.BEFORE, out before); if (before != null) { img.SpacingBefore = float.Parse(before); } String after = null; cssMap.TryGetValue(CSS.Property.AFTER, out after); if (after != null) { img.SpacingAfter = float.Parse(after); } img.WidthPercentage = 0; return img; }
iTextSharpImage(Image source) { this.source = source; }