C# iTextSharp,将多张图片合并生成PDF文件

发布时间 2023-05-05 14:29:29作者: 流纹

1、添加引用

首先添加NuGet引用

 

2、界面实现及按钮事件

        /// <summary>
        /// 根据图片生成PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_CreatePDF_ByPic_Click(object sender, EventArgs e)
        {
            var res = JPGConvertPDF($"C:\\Users\\lwk123456\\Desktop\\图片\\{ DateTime.Now.ToString("yyyy-MM-dd")}\\{Guid.NewGuid()}.pdf");
            MessageBox.Show(res.ToString());
        }

 

 3、具体方法

/// <summary>
/// 图片转PDF文档(将图片集成到PDF文件中)
/// </summary>
/// <param name="pdfpath">转换后的pdf路径</param>
/// <returns>true转换成功,false失败</returns>
public static bool JPGConvertPDF(string pdfPath)
{
    try
    {
        //调用文件选择框
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Multiselect = true;//等于true表示可以选择多个文件
        openFile.DefaultExt = "*.jpg";
        openFile.Filter = "图片|*.jpg";
        if (openFile.ShowDialog() == DialogResult.OK)
        {
            #region 文件夹目录处理
            string path = System.IO.Path.GetDirectoryName(pdfPath);
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            #endregion
            //尺寸为A4纸大小
            var PdfPageSize = iTextSharp.text.PageSize.A4;
            //Document为对象为页面对象,类似HTML页面
            var document = new iTextSharp.text.Document(PdfPageSize, 4, 25, 25, 25, 25);
            //创建并打开PDF
            var stream = new FileStream(pdfPath, FileMode.Create, FileAccess.Write, FileShare.None);
            //将Document对象写入PDF文件
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream);
            document.Open();
            if (openFile.FileNames != null && openFile.FileNames.Any())
            {
                foreach (string file in openFile.FileNames)
                {
                    //打开图片
                    var imageStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    var image = iTextSharp.text.Image.GetInstance(imageStream);
                    float height = document.Top - document.TopMargin;
                    //设置图片宽高缩放
                    var imageWidth = image.Width > document.Right ? document.Right : image.Width;
                    var imageHeight = image.Height > height ? height : image.Height;
                    image.ScaleToFit(imageWidth, imageHeight);
                    //图片高>A4纸高-25
                    if (image.Height > PdfPageSize.Height - 25)
                    {
                        image.ScaleToFit(PdfPageSize.Width - 25, PdfPageSize.Height - 25);
                    }
                    //图片宽>A4纸宽-25
                    else if (image.Width > PdfPageSize.Width - 25)
                    {
                        image.ScaleToFit(PdfPageSize.Width - 25, PdfPageSize.Height - 25);
                    }
                    image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
                    document.Add(image);
                    imageStream.Dispose();
                }
            }
            document.Close();
            document.Dispose();
            stream.Dispose();
        }
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}