【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 是用于诊断和调试的命名空间。
csharp 复制代码
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;

二、界面设计

三、代码

全局变量

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

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

选择文件夹的按钮

从Windows注册表中读取上次选择的文件夹路径。

显示一个文件夹选择对话框,让用户选择包含PDF文件的文件夹。

如果用户选择了一个文件夹,将该路径存储在inputFolderPath变量中,并创建(如果不存在)一个名为"Output"的子文件夹作为输出路径。

将选择的路径显示在文本框txtPath中。

csharp 复制代码
/// <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文件,并显示一个消息告知用户合并已完成,然后打开导出的文件夹供用户查看。

csharp 复制代码
/// <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"。
csharp 复制代码
 /// <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文件导出。

五、完整源码

csharp 复制代码
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);

        }

     }
}
相关推荐
FuLLovers29 分钟前
2024-09-13 冯诺依曼体系结构 OS管理 进程
linux·开发语言
everyStudy1 小时前
JS中判断字符串中是否包含指定字符
开发语言·前端·javascript
luthane1 小时前
python 实现average mean平均数算法
开发语言·python·算法
Hellc0071 小时前
什么是 WebApiEngine?
c#
dangoxiba2 小时前
【Unity学习心得】如何使用Unity制作“饥荒”风格的俯视角2.5D游戏
游戏·unity·c#·游戏引擎
凡人的AI工具箱2 小时前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python
sleP4o2 小时前
Python操作MySQL
开发语言·python·mysql
是店小二呀2 小时前
【C++】C++ STL探索:Priority Queue与仿函数的深入解析
开发语言·c++·后端
洛寒瑜2 小时前
【读书笔记-《30天自制操作系统》-23】Day24
开发语言·汇编·笔记·操作系统·应用程序
ephemerals__2 小时前
【c++】动态内存管理
开发语言·c++