C#递归合并PDF文件

情景:在某文件夹下有多个子文件夹,每个子文件夹中有多个PDF文件,分别将子文件夹下的PDF合并,并将合并的PDF命名为子文件夹名称,然后存在该子文件夹中。

由于文件夹下还有文件夹,因此需要用递归方法判定该文件夹下是否有PDF文件

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;  //引用的程序集

namespace beichuan
{
    class PDF123
    {
        // 合并PDF并修改合并后的文件名为文件所在文件夹名称
        // 文件夹下有多个多级子文件夹,最终文件夹下为两个pdf文件
        // filepath:根目录
        public void director(string filepath)
        {
            //绑定到指定的文件夹目录
            DirectoryInfo dir = new DirectoryInfo(filepath);
            //检索表示当前目录的文件和子目录
            FileSystemInfo[] fsinfos = dir.GetFileSystemInfos();
            //遍历检索的文件和子目录
            List<string> fileList = new List<string>();
            foreach (FileSystemInfo fsinfo in fsinfos)
            {
                //判断是否为空文件夹  
                if (fsinfo is DirectoryInfo)
                {
                    //递归调用
                    director(fsinfo.FullName);
                }
                else
                {
                    //将得到的文件全路径放入到集合中
                    fileList.Add(fsinfo.FullName);
                    string[] dirName = fileList[0].Split('\\');
                    string outMergeFile = Path.GetDirectoryName(fileList[0]) + "\\" + dirName[dirName.Length - 2] + ".pdf";
                    PdfReader reader;
                    Rectangle re;
                    Document document = new Document();
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
                    document.Open();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage newPage;
                    for (int i = 0; i < fileList.Count; i++)
                    {
                        reader = new PdfReader(fileList[i]);
                        int iPageNum = reader.NumberOfPages;
                        for (int j = 1; j <= iPageNum; j++)
                        {
                            re = reader.GetPageSize(reader.GetPageN(j)); //获取当前页面的纸张方向
                            document.SetPageSize(re); //设置新PDF当前页面的纸张方向
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            cb.AddTemplate(newPage, 0, 0);
                        }
                    }
                    document.Close();
                }
            }
        }
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值