【C#】C#实现PDF合并


一、下载iTextSharp.dll

下载iTextSharp.dll

可使用联机方式或者文件下载方式。
在这里插入图片描述

命名空间引入

代码开始时引入了一些命名空间,这些命名空间包含了程序运行所需的类和方法。

  • System、System.Collections.Generic、System.ComponentModel等是.NET框架的核心命名空间。
  • iTextSharp.text 和 iTextSharp.text.pdf 是用于处理PDF文件的库。
  • System.IO 是用于文件和目录操作的命名空间。
  • Microsoft.Win32 是用于访问Windows注册表的命名空间。
  • System.Diagnostics 是用于诊断和调试的命名空间。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;

二、界面设计

在这里插入图片描述

三、代码

全局变量

定义了三个静态字符串变量,用于存储上次选择的文件夹路径、输入文件夹路径和输出文件夹路径。

// 全局变量
        private static string lastFolderPath = ""; // 记录上次选择文件夹的路径
        private static string inputFolderPath = ""; // 输入文件夹路径
        private static string outputFolderPath = ""; // 输出文件夹路径

选择文件夹的按钮

从Windows注册表中读取上次选择的文件夹路径。
显示一个文件夹选择对话框,让用户选择包含PDF文件的文件夹。
如果用户选择了一个文件夹,将该路径存储在inputFolderPath变量中,并创建(如果不存在)一个名为"Output"的子文件夹作为输出路径。
将选择的路径显示在文本框txtPath中。

/// <summary>
        /// 按钮,选择文件夹路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectPath_Click(object sender, EventArgs e)
        {
            // 读取上次选择的文件夹路径  
            string registryKey = "Software\\PDF合并"; // 用您自己的应用程序名称替换YourAppName  
            if (Registry.CurrentUser.OpenSubKey(registryKey) != null)
            {
                lastFolderPath = Registry.CurrentUser.OpenSubKey(registryKey).GetValue("LastFolder") as string;
            }

            // 创建并显示一个选择文件夹的对话框  
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            folderDialog.Description = "选择包含PDF文件的文件夹:";
            folderDialog.SelectedPath = lastFolderPath; // 设置默认路径为用户上次选择的文件夹  

            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户选择的文件夹路径  
                inputFolderPath = folderDialog.SelectedPath;

                // 创建输出文件夹路径(如果它不存在则创建它)  
                outputFolderPath = Path.Combine(inputFolderPath, "Output");

                if (!Directory.Exists(outputFolderPath))
                {
                    Directory.CreateDirectory(outputFolderPath);
                }
            }

            txtPath.Text = inputFolderPath;
        }

确认合并的按钮

简而言之,当用户点击“确认合并PDF”按钮时,此方法首先检查用户是否已选择了一个路径。如果没有,它会提示用户选择一个路径;如果已选择,它会调用一个方法来合并PDF文件,并显示一个消息告知用户合并已完成,然后打开导出的文件夹供用户查看。

/// <summary>
        /// 按钮,确认合并PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtPath.Text == string.Empty)
            {
                MessageBox.Show("请选择要合并的文件夹路径!");
            }
            else
            {
                // 调用合并PDF的方法  
                MergePDFs(inputFolderPath, outputFolderPath, "123");

                MessageBox.Show("合并完成!");

                // 打开导出的文件夹路径  
                Process.Start(outputFolderPath);
            }
        }
  • 合并PDF的处理函数
    定义方法:public void MergePDFs(string inputFolderPath, string outputFolderPath, string outputPdfName)
    获取输入文件夹中所有的PDF文件,并将它们存储在inputFiles字符串数组中。
    创建输出PDF文件的路径,使用Path.Combine方法将输出文件夹路径和输出PDF文件名称组合起来。
    创建一个新的文件流stream,并使用FileStream类以写入模式打开它,准备写入输出PDF文件。
    创建一个新的Document对象pdfDoc,表示输出PDF文件。
    创建一个新的PdfCopy对象pdf,用于将内容复制到输出PDF文件中。
    打开输出PDF文档以进行写入。
    遍历所有输入的PDF文件,并使用PdfReader对象读取每个PDF文件。
    对于每个输入的PDF文件,获取其页面数,并使用for循环遍历每个页面。
    将每个输入PDF文件的页面添加到输出PDF文件中。
    检查输出PDF文档是否为空,如果不为空则关闭它。
    关闭文件流。
    创建新输出PDF文件的完整路径。
    检查新输出文件是否已存在,如果已存在则删除它。
    将原输出文件移动到新位置并重命名为"AllPDF_Merged.pdf"。
 /// <summary>
        /// 合并多个PDF文件为一个PDF文件
        /// </summary>
        /// <param name="inputFolderPath"></param>
        /// <param name="outputFolderPath"></param>
        /// <param name="outputPdfName"></param>
        public void MergePDFs(string inputFolderPath, string outputFolderPath, string outputPdfName)
        {
            // 获取输入文件夹中所有的PDF文件  
            string[] inputFiles = Directory.GetFiles(inputFolderPath, "*.pdf");

            // 创建输出PDF文件路径  
            string outputPdfPath = Path.Combine(outputFolderPath, outputPdfName);

            // 创建输出PDF文件  
            using (FileStream stream = new FileStream(outputPdfPath, FileMode.Create))
            {
                Document pdfDoc = new Document();
                PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();

                foreach (string file in inputFiles)
                {
                    // 读取每个PDF文件并将其页面添加到输出PDF中  
                    PdfReader reader = new PdfReader(file);
                    int n = reader.NumberOfPages;
                    for (int i = 1; i <= n; i++)
                    {
                        pdf.AddPage(pdf.GetImportedPage(reader, i));
                    }
                    reader.Close();
                }

                if (pdfDoc != null) pdfDoc.Close();
                stream.Close();
            }

            string newOutputPdfPath = Path.Combine(outputFolderPath, "AllPDF_Merged.pdf");

            // 检查新输出文件是否已存在  
            if (File.Exists(newOutputPdfPath))
            {
                // 如果已存在,则删除旧文件并创建新文件  
                File.Delete(newOutputPdfPath);
            }

            // 重命名输出PDF文件  
            File.Move(outputPdfPath, newOutputPdfPath);

        }

四、导出结果

可将一个文件夹内的所有PDF合并成一个PDF文件导出。

在这里插入图片描述

五、完整源码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;

namespace PDF合并
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 全局变量
        private static string lastFolderPath = ""; // 记录上次选择文件夹的路径
        private static string inputFolderPath = ""; // 输入文件夹路径
        private static string outputFolderPath = ""; // 输出文件夹路径


        /// <summary>
        /// 按钮,选择文件夹路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectPath_Click(object sender, EventArgs e)
        {
            // 读取上次选择的文件夹路径  
            string registryKey = "Software\\PDF合并"; // 用您自己的应用程序名称替换YourAppName  
            if (Registry.CurrentUser.OpenSubKey(registryKey) != null)
            {
                lastFolderPath = Registry.CurrentUser.OpenSubKey(registryKey).GetValue("LastFolder") as string;
            }

            // 创建并显示一个选择文件夹的对话框  
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            folderDialog.Description = "选择包含PDF文件的文件夹:";
            folderDialog.SelectedPath = lastFolderPath; // 设置默认路径为用户上次选择的文件夹  

            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户选择的文件夹路径  
                inputFolderPath = folderDialog.SelectedPath;

                // 创建输出文件夹路径(如果它不存在则创建它)  
                outputFolderPath = Path.Combine(inputFolderPath, "Output");

                if (!Directory.Exists(outputFolderPath))
                {
                    Directory.CreateDirectory(outputFolderPath);
                }
            }

            txtPath.Text = inputFolderPath;
        }

        /// <summary>
        /// 按钮,确认合并PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtPath.Text == string.Empty)
            {
                MessageBox.Show("请选择要合并的文件夹路径!");
            }
            else
            {
                // 调用合并PDF的方法  
                MergePDFs(inputFolderPath, outputFolderPath, "123");

                MessageBox.Show("合并完成!");

                // 打开导出的文件夹路径  
                Process.Start(outputFolderPath);
            }
        }

        /// <summary>
        /// 合并多个PDF文件为一个PDF文件
        /// </summary>
        /// <param name="inputFolderPath"></param>
        /// <param name="outputFolderPath"></param>
        /// <param name="outputPdfName"></param>
        public void MergePDFs(string inputFolderPath, string outputFolderPath, string outputPdfName)
        {
            // 获取输入文件夹中所有的PDF文件  
            string[] inputFiles = Directory.GetFiles(inputFolderPath, "*.pdf");

            // 创建输出PDF文件路径  
            string outputPdfPath = Path.Combine(outputFolderPath, outputPdfName);

            // 创建输出PDF文件  
            using (FileStream stream = new FileStream(outputPdfPath, FileMode.Create))
            {
                Document pdfDoc = new Document();
                PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();

                foreach (string file in inputFiles)
                {
                    // 读取每个PDF文件并将其页面添加到输出PDF中  
                    PdfReader reader = new PdfReader(file);
                    int n = reader.NumberOfPages;
                    for (int i = 1; i <= n; i++)
                    {
                        pdf.AddPage(pdf.GetImportedPage(reader, i));
                    }
                    reader.Close();
                }

                if (pdfDoc != null) pdfDoc.Close();
                stream.Close();
            }

            string newOutputPdfPath = Path.Combine(outputFolderPath, "AllPDF_Merged.pdf");

            // 检查新输出文件是否已存在  
            if (File.Exists(newOutputPdfPath))
            {
                // 如果已存在,则删除旧文件并创建新文件  
                File.Delete(newOutputPdfPath);
            }

            // 重命名输出PDF文件  
            File.Move(outputPdfPath, newOutputPdfPath);

        }

     }
}




以下为一些扩展代码,以及PDF合并的应用:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
namespace PDF合并
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // 全局变量
        private static string lastFolderPath = ""; // 记录上次选择文件夹的路径
        private static string inputFolderPath = ""; // 输入文件夹路径
        private static string outputFolderPath = ""; // 输出文件夹路径
        // 生成目录相关
        List<string> listFileName = new List<string>(); // 所有文件文件名
        List<int> listFileFirstPageNum = new List<int>(); // 所有文件起始页的页码
        int countPage = 0; // 所有的页面累加
        /// <summary>
        /// 按钮,选择文件夹路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectPath_Click(object sender, EventArgs e)
        {
            // 读取上次选择的文件夹路径  
            string registryKey = "Software\\PDF合并"; // 用您自己的应用程序名称替换YourAppName  
            if (Registry.CurrentUser.OpenSubKey(registryKey) != null)
            {
                lastFolderPath = Registry.CurrentUser.OpenSubKey(registryKey).GetValue("LastFolder") as string;
            }
            // 创建并显示一个选择文件夹的对话框  
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            folderDialog.Description = "选择包含PDF文件的文件夹:";
            folderDialog.SelectedPath = lastFolderPath; // 设置默认路径为用户上次选择的文件夹  
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户选择的文件夹路径  
                inputFolderPath = folderDialog.SelectedPath;
                // 创建输出文件夹路径(如果它不存在则创建它)  
                outputFolderPath = Path.Combine(inputFolderPath, "Output");
                // 创建输出路径
                if (!Directory.Exists(outputFolderPath))
                {
                    Directory.CreateDirectory(outputFolderPath);
                }
            }
            txtPath.Text = inputFolderPath;
        }
        /// <summary>
        /// 按钮,确认合并PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtPath.Text == string.Empty)
            {
                MessageBox.Show("请选择要合并的文件夹路径!");
            }
            else
            {
                try
                {
                    Directory.Delete(outputFolderPath, true);
                    Directory.CreateDirectory(outputFolderPath); // 每次重置输出文件夹
                }
                catch (Exception ex)
                {
                    MessageBox.Show("当前处理的PDF文件已打开,请关闭后重新处理!" + ex.ToString());
                    return;
                }
                // 调用合并PDF的方法  
                MergePDFs(inputFolderPath, outputFolderPath, "123");
                MessageBox.Show("合并完成!");
                // 打开导出的文件夹路径  
                Process.Start(outputFolderPath);
            }
        }
        /// <summary>
        /// 合并多个PDF文件为一个PDF文件
        /// </summary>
        /// <param name="inputFolderPath"></param>
        /// <param name="outputFolderPath"></param>
        /// <param name="outputPdfName"></param>
        public void MergePDFs(string inputFolderPath, string outputFolderPath, string outputPdfName)
        {
            // 每次合并前先清空目录信息
            listFileName.Clear();
            listFileFirstPageNum.Clear();
            countPage = 0;
            // 获取输入文件夹中所有的PDF文件  
            //string[] inputFiles = Directory.GetFiles(inputFolderPath, "*.pdf");
            string[] inputFiles = GetAllPdfFiles(inputFolderPath);
            // 创建输出PDF文件路径  
            string outputPdfPath = Path.Combine(outputFolderPath, outputPdfName);
            // 创建输出PDF文件  
            using (FileStream stream = new FileStream(outputPdfPath, FileMode.Create))
            {
                Document pdfDoc = new Document();
                PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();
                foreach (string file in inputFiles)
                {
                    // 读取每个PDF文件并将其页面添加到输出PDF中  
                    PdfReader reader = new PdfReader(file);
                    int n = reader.NumberOfPages;
                    for (int i = 1; i <= n; i++)
                    {
                        pdf.AddPage(pdf.GetImportedPage(reader, i));
                        countPage++; // 总页面累加
                    }
                    reader.Close();
                    listFileFirstPageNum.Add(countPage); // 添加每个文件起始页的页码
                    string fileName = Path.GetFileName(file);
                    listFileName.Add(fileName.Split('.')[0]); // 添加每个文件的名称
                }
                if (pdfDoc != null)
                {
                    pdfDoc.Close();
                } 
                stream.Close();
            }
            string newOutputPdfPath = Path.Combine(outputFolderPath, "AllPDF_Merged.pdf");
            // 检查新输出文件是否已存在  
            if (File.Exists(newOutputPdfPath))
            {
                // 如果已存在,则删除旧文件并创建新文件  
                File.Delete(newOutputPdfPath);
            }
            // 重命名输出PDF文件  
            File.Move(outputPdfPath, newOutputPdfPath);
            // 添加页码  参数是输入文件、输出文件
            PdfAddPageNumber(newOutputPdfPath, Path.Combine(outputFolderPath, "MergedWithPageNumbers.pdf"));  
            // 目录需要封面信息和每个文件第一页开始的页码。 文件名、文件名对应的第一个页码、最开始添加页并能放得下页信息
            CreatePdfCatalogue(listFileName, listFileFirstPageNum, outputFolderPath);
        }
        // 递归函数,用于从给定文件夹及其所有子文件夹中获取所有PDF文件  
        private string[] GetAllPdfFiles(string folderPath)
        {
            List<string> pdfFiles = new List<string>();
            // 获取指定文件夹中的所有PDF文件路径,并添加到列表中  
            string[] files = Directory.GetFiles(folderPath, "*.pdf");
            pdfFiles.AddRange(files);
            // 遍历文件夹中的每个子文件夹,并递归调用GetAllPdfFiles函数以获取子文件夹中的PDF文件路径,然后添加到列表中  
            foreach (string subDir in Directory.GetDirectories(folderPath))
            {
                pdfFiles.AddRange(GetAllPdfFiles(subDir));
            }
            // 将PDF文件路径列表转换为数组并返回  
            return pdfFiles.ToArray();
        }
        /// <summary>
        /// 生成目录PDF
        /// </summary>
        /// <param name="fileNames"></param>
        /// <param name="filePageNums"></param>
        /// <param name="outputPath"></param>
        private void CreatePdfCatalogue(List<string> fileNames, List<int> filePageNums, string outputPath)
        {
            // 创建PDF文件
            FileStream pdfFs = new FileStream(Path.Combine(outputPath, "目录.pdf"), FileMode.Create);
            // 获取实例
            Document doc = new Document();
            doc.SetPageSize(PageSize.A4.Rotate()); // 设置页面横向
            doc.SetMargins(50, 50, 30, 30);
            PdfWriter writer = PdfWriter.GetInstance(doc, pdfFs);
            // 打开pdf
            doc.Open();
            // 基本字体信息,可显示中文
            BaseFont bfChinese = BaseFont.CreateFont(@"C:\Windows\Fonts\simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 设置基础字体
            Paragraph paragCatalog = new Paragraph("目录\n\n", new iTextSharp.text.Font(bfChinese, 30)); // 设置目录段落的内容和字体
            paragCatalog.Alignment = Element.ALIGN_CENTER; // 目录居中对齐
            doc.Add(paragCatalog); // 添加目录名称
            for (int i = 0; i < fileNames.Count; i++)
            {
                string rowInfo = (i + 1).ToString() + " " + fileNames[i] + "............";
                Paragraph paragInfo = new Paragraph(rowInfo, new iTextSharp.text.Font(bfChinese, 14)); // 设置目录条目内容和字体
                paragInfo.Alignment=Element.ALIGN_LEFT;
                doc.Add(paragInfo); // 添加每一条目录信息
                Paragraph paragInfo2 = new Paragraph((i + 1).ToString() + "." + filePageNums[i].ToString(), new iTextSharp.text.Font(bfChinese, 14)); // 设置目录条目内容和字体
                paragInfo2.Alignment = Element.ALIGN_RIGHT;
                doc.Add(paragInfo2); // 添加每一条目录信息
            }
            if (doc != null)
            {
                doc.Close();
            }
            if (pdfFs != null)
            {
                pdfFs.Close();
            }
        }
         /// <summary>
        /// 添加页码
        /// </summary>
        /// <param name="pdfPath">pdf文件</param>
        /// <param name="outPath">输出文件位置</param>
        public static void PdfAddPageNumber(string pdfPath, string outPath)
        {
            //读取pdf
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(pdfPath);
            //创建新pdf
            System.IO.Stream outStream = new System.IO.FileStream(outPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);
            iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, outStream); ;
            int pdfTotalPage = reader.NumberOfPages;//总页数
            //第一页pdf尺寸
            iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
            iTextSharp.text.pdf.PdfContentByte content;
            //【C:\WINDOWS\Fonts】系统字体存放位置
            iTextSharp.text.pdf.BaseFont font = iTextSharp.text.pdf.BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.EMBEDDED);
            iTextSharp.text.pdf.PdfGState gs = new iTextSharp.text.pdf.PdfGState();
            ///添加页码
            for (int i = 1; i <= pdfTotalPage; i++)
            {
                content = stamper.GetOverContent(i);//添加在内容上层,GetUnderContent内容下层
                gs.FillOpacity = 0.8f;//设置透明度
                content.SetGState(gs);
                content.BeginText();
                content.SetColorFill(iTextSharp.text.BaseColor.BLACK);//设置字体颜色
                content.SetFontAndSize(font, 10);//设置字体大小
                content.ShowTextAligned(iTextSharp.text.Element.ALIGN_BASELINE, "第" + i + "页,共" + pdfTotalPage + "页", width / 2 - 15, 12, 0);//设置字体添加位置
                content.EndText();
            }
            stamper.Close();
            reader.Close();
        }
     }
}

  • 24
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值