【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);

        }

     }
}

相关推荐

  1. PDF合并】利用 Python 合并 PDF 文件

    2024-01-10 07:58:02       41 阅读
  2. PDF分割合并

    2024-01-10 07:58:02       27 阅读
  3. python 合并 pdf

    2024-01-10 07:58:02       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-10 07:58:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-10 07:58:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-10 07:58:02       87 阅读
  4. Python语言-面向对象

    2024-01-10 07:58:02       96 阅读

热门阅读

  1. 算法训练day10字符串总结双指针回顾

    2024-01-10 07:58:02       56 阅读
  2. 【力扣100】20.有效的括号 || 栈

    2024-01-10 07:58:02       70 阅读
  3. Hadoop之mapreduce参数大全-4

    2024-01-10 07:58:02       35 阅读
  4. apache共享目录文件配置

    2024-01-10 07:58:02       61 阅读
  5. 【困难】42. 接雨水

    2024-01-10 07:58:02       54 阅读
  6. MySQL面试系列-02

    2024-01-10 07:58:02       54 阅读
  7. 数据分析---SQL

    2024-01-10 07:58:02       59 阅读
  8. 【Web】 CSS引用方式

    2024-01-10 07:58:02       55 阅读