用其中一个就行,第一个测试正常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
第一个试了完美 //合并多个PDF public static void MergePdfFiles(string outputFilePath, params string[] inputFilePaths) { try { inputFilePaths = inputFilePaths.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); //先去掉空值 // 创建一个新的PDF文档用于合并 PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument(); foreach (string inputFile in inputFilePaths) { // 加载要合并的PDF PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(inputFile, PdfDocumentOpenMode.Import); // 将每个PDF的页面添加到输出文档中 for (int pageIndex = 0; pageIndex < inputDocument.PageCount; pageIndex++) { PdfSharp.Pdf.PdfPage page = inputDocument.Pages[pageIndex]; outputDocument.AddPage(page); } // 关闭输入文档 //inputDocument.Close(); } // 保存合并后的PDF文件 outputDocument.Save(outputFilePath); outputDocument.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } } //这个试了不能铺满,不知什么原因 // 合并多个PDF /// <param name="SourcePath">源路径</param> /// <param name="TargetPath">目标路径</param> /// <param name="NewFileName">新文件名</param> public static void MergePDF(string SourcePath, string outputFilePath) { //需要合并的pdf集合 string[] fileList = Directory.GetFiles(SourcePath, "*.pdf", SearchOption.AllDirectories); //合并到的总PDF iTextSharp.text.pdf.PdfReader reader; iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFilePath, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage newPage; for (int i = 0; i < fileList.Length; i++) { reader = new iTextSharp.text.pdf.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(); } |
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。