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#9.0:Init相关总结

    C#9.0:Init相关总结

    这篇文章主要介绍了C#9.0:Init的相关资料,帮助大家更好的理解和学习新版的c#,感兴趣的朋友可以了解下
    2021-02-02
  • c#基础之数组与接口使用示例(遍历数组 二维数组)

    c#基础之数组与接口使用示例(遍历数组 二维数组)

    本文主要介绍了c#基础知识中的数组与接口使用方法,结合示例,大家一看就明白
    2014-01-01
  • 浅析C#中静态方法和非静态方法的区别

    浅析C#中静态方法和非静态方法的区别

    C#静态方法与非静态方法的区别不仅仅是概念上的,那么他们有什么具体的区别呢?让我们通过本文向大家介绍下C#中静态方法和非静态方法的区别,一起看看吧
    2017-09-09
  • 深入理解C♯ 7.0中的Tuple特性

    深入理解C♯ 7.0中的Tuple特性

    这篇文章主要介绍了C#7中Tuple特性的相关资料,文中通过示例代码介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友可以们下面来一起学习学习吧。
    2017-03-03
  • C# WinForm导出Excel方法介绍

    C# WinForm导出Excel方法介绍

    在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式
    2013-12-12
  • C#获取远程XML文档的方法

    C#获取远程XML文档的方法

    这篇文章主要介绍了C#获取远程XML文档的方法,涉及C#文件传输与XML文档操作相关技巧,需要的朋友可以参考下
    2016-01-01
  • c#动态加载卸载DLL的方法

    c#动态加载卸载DLL的方法

    这篇文章介绍了c#动态加载卸载DLL的方法,有需要的朋友可以参考一下
    2013-11-11
  • C#中DropDownList动态生成的方法

    C#中DropDownList动态生成的方法

    这篇文章主要介绍了C#中DropDownList动态生成的方法,实例分析了C#中DropDownList的使用技巧,非常具有实用价值,需要的朋友可以参考下
    2015-03-03
  • C#中的IEnumerable接口深入研究

    C#中的IEnumerable接口深入研究

    这篇文章主要介绍了.NET中的IEnumerable接口深入研究,分析出了它的实现原理和实现代码,需要的朋友可以参考下
    2014-07-07
  • C#之WinForm WebBrowser实用技巧汇总

    C#之WinForm WebBrowser实用技巧汇总

    这篇文章主要介绍了C#之WinForm WebBrowser实用技巧汇总,包括常见的各种设置及信息获取等,需要的朋友可以参考下
    2014-08-08

最新评论