C#实现PDF合并的项目实践

 更新时间:2024年01月10日 15:18:30   作者:JosieBook  
有时我们可能会遇到需要的资料或教程被分成了几部分存放在多个PDF文件中,本文主要介绍了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);

        }

     }
}

到此这篇关于C#实现PDF合并的项目实践的文章就介绍到这了,更多相关C# PDF合并内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • 浅析C#中不同格式请求的区别

    浅析C#中不同格式请求的区别

    form-data 请求和 x-www-form-urlencoded 请求是两种常见的 HTTP 请求体格式,这篇文章主要为大家详细介绍了二者的区别与应用,希望对大家有所帮助
    2023-08-08
  • 在Winform动态启动、控制台命令行的方法

    在Winform动态启动、控制台命令行的方法

    winForm 程序输出类型为 windows 程序(不是命令行程序)在运行时想输入一些信息编译开发调试,如何实现这一功能
    2013-02-02
  • C#代码实现在Excel中创建雷达图

    C#代码实现在Excel中创建雷达图

    本文演示了如何在 C# 中创建填充型雷达图,通过设置数据、样式与图表属性,实现多维数据的可视化展示,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下
    2026-05-05
  • C#实现的SQL备份与还原功能示例

    C#实现的SQL备份与还原功能示例

    这篇文章主要介绍了C#实现的SQL备份与还原功能,结合具体实例形式分析了C#操作数据库实现SQL备份与还原相关的控件、SQL连接、文件等操作技巧,需要的朋友可以参考下
    2017-06-06
  • 重温C# clr 笔记总结

    重温C# clr 笔记总结

    本篇文章是对以前学习C# clr做的一些笔记,现在拿出来和大家分享下,希望需要的朋友能参考一下
    2013-05-05
  • WPF通过线程使用ProcessBar的方法详解

    WPF通过线程使用ProcessBar的方法详解

    这篇文章主要给大家介绍了关于WPF通过线程使用ProcessBar的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用WPF具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-04-04
  • C#难点逐个击破(2):out返回参数

    C#难点逐个击破(2):out返回参数

    之前提到ref是将原方法中的参数影响的结果返回到调用它的方法中,out与ref类似,相比之下,ref传递参数的地址,out是返回值。
    2010-02-02
  • C#文件读写操作详细操作指南

    C#文件读写操作详细操作指南

    这篇文章主要给大家介绍了关于C#文件读写操作详细操作指南,在后端开发中使用C#语言进行文件操作是一个常见的任务,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-10-10
  • Silverlight实现星星闪烁动画

    Silverlight实现星星闪烁动画

    这篇文章主要为大家详细介绍了Silverlight实现星星闪烁动画,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-07-07
  • C#使用Lazy实现延迟加载的方法示例

    C#使用Lazy实现延迟加载的方法示例

    在C#中,Lazy< T> 类是一个非常有用的工具,它可以用于延迟加载值,在本文中,我们将详细介绍 Lazy< T> 的实现机制和用法,并提供一些示例来展示它的优势,文中通过代码示例讲解的非常详细,需要的朋友可以参考下
    2024-06-06

最新评论