需先引用 itextsharp.dll
//方法一 /// <summary> /// JPG转PDF /// </summary> /// <param name="jpgfile">图片路径</param> /// <param name="pdf">生成的PDF路径</param> /// <param name="pageSize">A4,A5</param> /// <param name="Vertical">True:纵向,False横向</param> public void ConvertJPG2PDF(string jpgfile, string pdf, string pageSize, bool Vertical = true) { float width = 0, height = 0; Document document; #region 根据纸张大小,纵横向,设置画布长宽 if (pageSize.ToUpper() == "A4") { if (Vertical)//纵向 { width = iTextSharp.text.PageSize.A4.Width; height = iTextSharp.text.PageSize.A4.Height; } else//横向 { width = iTextSharp.text.PageSize.A4.Height; height = iTextSharp.text.PageSize.A4.Width; } } else if (pageSize.ToUpper() == "A5") { if (Vertical) { width = iTextSharp.text.PageSize.A5.Width; height = iTextSharp.text.PageSize.A5.Height; } else { width = iTextSharp.text.PageSize.A5.Height; height = iTextSharp.text.PageSize.A5.Width; } } iTextSharp.text.Rectangle pageSizeNew = new iTextSharp.text.Rectangle(width, height); document = new Document(pageSizeNew); #endregion using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)) { PdfWriter.GetInstance(document, stream); document.Open(); using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var image = iTextSharp.text.Image.GetInstance(imageStream); //缩放图像比例 image.ScaleToFit(width, height); image.SetAbsolutePosition(0, 0); image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); } document.Close(); } }
//方法二 /// <summary> /// jpg转PDF /// </summary> /// <param name="pdfPath">pdf存放路径</param> /// <param name="jpegPath">jpg路径</param> /// <returns></returns> private bool jpegTopdf(string pdfPath, string jpegPath) { try { System.Drawing.Image B = System.Drawing.Image.FromFile(jpegPath); System.Drawing.Bitmap image = new System.Drawing.Bitmap(B); B.Dispose(); Document document = new Document(); //document.SetPageSize(new iTextSharp.text.Rectangle(image.Width + 72f, image.Height + 72f)); document.SetPageSize(new iTextSharp.text.Rectangle(image.Width, image.Height)); PdfWriter write = PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.OpenOrCreate, FileAccess.Write)); document.Open(); iTextSharp.text.Image jpg; jpg = iTextSharp.text.Image.GetInstance(image, ImageFormat.Jpeg); document.NewPage(); document.Add(jpg); if (document != null && document.IsOpen()) { document.Close(); } if (write != null) { write.Close(); } return true; } catch (Exception ex) { return false; } }
标签:PageSize,C#,text,image,JPG,iTextSharp,new,PDF,document From: https://www.cnblogs.com/lydj/p/17123861.html