C# JPG转PDF
生活随笔
收集整理的這篇文章主要介紹了
C# JPG转PDF
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
需先引用 itextsharp.dll
//方法一 /// <summary>/// JPG轉(zhuǎn)PDF/// </summary>/// <param name="jpgfile">圖片路徑</param>/// <param name="pdf">生成的PDF路徑</param>/// <param name="pageSize">A4,A5</param>/// <param name="Vertical">T:縱向,F橫向</param>public void ConvertJPG2PDF(string jpgfile, string pdf, string pageSize, bool Vertical = true){float width = 0, height = 0;Document document;#region 根據(jù)紙張大小,縱橫向,設(shè)置畫布長寬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轉(zhuǎn)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;}}總結(jié)
以上是生活随笔為你收集整理的C# JPG转PDF的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle SQL Loader数据导
- 下一篇: C语言中执行python代码或源程序文件