C#利用PdfSharp图片生成PDF文件

1、创建一个winform程序,安装PdfSharp 1.50.5147

 2、添加一个按钮,代码如下

复制代码
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System;
using System.IO;
using System.Windows.Forms;

namespace PDFWin
{
    public partial class Form1 : Form
    {
        private static string sysPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        private string imgDir = sysPath + "img\\";  //图片放置的地方,总共10张,图片名称按1.jpg\2.jpg...命名
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[][] buffer = new byte[10][];
            for (int i = 1; i <= 10; i++)  //图片转字节存到数组
            {
                string imgPath = $"{imgDir}{i}.jpg";
                byte[] b = System.IO.File.ReadAllBytes(imgPath);
                buffer[i-1] = b;
            }

            //图片生成PDF
            SavePdf(buffer, $"{imgDir}{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.pdf");
        }

        /// <summary>
        /// 保存PDF图像
        /// </summary>
        /// <param name="buffer">要处理的所有图片数据</param>
        /// <param name="path">PDF的保存路径</param>
        /// <returns></returns>
        public static void SavePdf(byte[][] buffer, string savePath)
        {
            if (buffer == null || buffer.Length == 0)
            {
                throw new Exception("文件流为空!");
            }
           

            string folderPath = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            PdfDocument doc = new PdfDocument();
            try
            {
                for (int i = 0; i < buffer.Length; i++)
                {
                    using (MemoryStream ms1 = new MemoryStream(buffer[i]))
                    {
                        XImage img = XImage.FromStream(ms1);
                        PdfPage page = doc.AddPage();
                        XGraphics xgr = XGraphics.FromPdfPage(page);
                        xgr.DrawImage(img, 0, 0, page.Width.Value, page.Height.Value);//切记这里一定要指定宽高

                        img.Dispose();
                    }
                }
                doc.Save(savePath);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                doc.Dispose();
                doc.Close();
            }
        }
    }
}
View Code
复制代码

 

参考官网DEMO

PDFsharp Samples - PDFsharp and MigraDoc Wiki

 

posted @   ziff123  阅读(848)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示