C#使用iTextSharp将图片转为pdf


最近接到的工作 

1.word转PDF

2.PDF添加水印,并控制显示的页数

3.JPG转PDF

 

在NuGet里面搜索 iTextSharp 安装

/// <summary>
        /// 图片转PDF
        /// </summary>
        /// <param name="jpgfile">图片本地地址</param>
        /// <param name="pdf">生成的文件路径和文件名</param>
        /// <returns></returns>
        public static bool ConvertJPG2PDF(string jpgfile, string pdf)
        {
            var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
            using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None))
            {
          //这里加try catch 是因为这个地方我用的时候会报错 但是不影响使用
try { iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); } catch (Exception ex) { } document.Open(); using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var 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 true; }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM