c# 将多个PDF文件合并成一个
引用 iTextSharp.text
/// <summary>
/// 调用方法
/// </summary>
public static void button1_Click()
{
string path_Source = @"C:\Users\Administrator\Desktop\原始备份\原始备份";//PDF文档文件夹位置
string path_Target = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//计算机桌面的路径
MergePDF(path_Source, path_Target, "PDF总文档.pdf");
}
#region 合并多个PDF
/// <param name="SourcePath">源路径</param>
/// <param name="TargetPath">目标路径</param>
/// <param name="NewFileName">新文件名</param>
private static void MergePDF(string SourcePath, string TargetPath, string NewFileName)
{
//需要合并的pdf集合
string[] fileList = Directory.GetFiles(SourcePath, "*.pdf", SearchOption.AllDirectories);
//合并到的总PDF
string outMergeFile = TargetPath + "\\" + NewFileName;
PdfReader reader;
iTextSharp.text.Document document = new iTextSharp.text.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.Length; i++)
{
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();
}
#endregion
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期