将一个目录中所有PDF文件合并到一个新的PDF文件中

本文介绍了一种使用C#和iTextSharp库实现的PDF文件批量合并方法。通过该方法可以将指定目录下的所有PDF文件合并成一个PDF文件。文中提供了完整的代码示例,包括如何读取PDF文件、创建新的PDF文档并逐页添加原有PDF的内容。

将一个目录中所有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;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;//这个dll要引用
using iTextSharp.text.pdf;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            mergePDFFiles(tb_path.Text, tb_result.Text);
        }
        /// <summary>
        /// PDF合并
        /// </summary>
        /// <param name="fileList">需要合并的PDF文件路径</param>
        /// <param name="outMergeFile">合并保存输出路径</param>
        public void mergePDFFiles(string filePath, string outMergeFile)
        {
            PdfReader reader;
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage newPage;
            string[] fileList = System.IO.Directory.GetFiles(filePath, "*.pdf");
            for (int i = 0; i < fileList.Length; i++)
            {
                if (!File.Exists(fileList[i]))
                    continue;

                reader = new PdfReader(fileList[i]);
                int iPageNum = reader.NumberOfPages;
                for (int j = 1; j <= iPageNum; j++)
                {
                    document.NewPage();
                    newPage = writer.GetImportedPage(reader, j);
                    cb.AddTemplate(newPage, 0, 0);
                }
            }
            document.Close();
        }

    }
}

转载于:https://www.cnblogs.com/swtool/p/3832411.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值