情景:在某文件夹下有多个子文件夹,每个子文件夹中有多个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();
}
}
}
}
}