Csharp/C#教程:C#iTextSharp通过字节数组合并多个pdf分享


C#iTextSharp通过字节数组合并多个pdf

我是新手使用iTextSharp并且一般使用Pdf文件,但我认为我走在正确的轨道上。

我遍历一个pdf文件列表,将它们转换为字节,并将所有结果字节推送到字节数组中。 从那里我将字节数组传递给concatAndAddContent()以将所有pdf合并为单个大型pdf。 目前我刚刚获得列表中的最后一个pdf(它们似乎被覆盖)

public static byte[] concatAndAddContent(List pdfByteContent) { byte[] allBytes; using (MemoryStream ms = new MemoryStream()) { Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, ms); doc.SetPageSize(PageSize.LETTER); doc.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; PdfReader reader; foreach (byte[] p in pdfByteContent) { reader = new PdfReader(p); int pages = reader.NumberOfPages; // loop over document pages for (int i = 1; i <= pages; i++) { doc.SetPageSize(PageSize.LETTER); doc.NewPage(); page = writer.GetImportedPage(reader, i); cb.AddTemplate(page, 0, 0); } } doc.Close(); allBytes = ms.GetBuffer(); ms.Flush(); ms.Dispose(); } return allBytes; } 

上面是工作代码,导致创建单个pdf,其余文件被忽略。 有什么建议

这几乎只是Bruno代码的C#版本。

这是合并PDF文件的最简单,最安全和推荐的方法。 PdfSmartCopy对象能够检测多个文件中的冗余,这可以减少文件大小一些时间。 其中一个重载接受一个完整的PdfReader对象,可以根据需要进行实例化。

上述就是C#学习教程:C#iTextSharp通过字节数组合并多个pdf分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public static byte[] concatAndAddContent(List pdfByteContent) { using (var ms = new MemoryStream()) { using (var doc = new Document()) { using (var copy = new PdfSmartCopy(doc, ms)) { doc.Open(); //Loop through each byte array foreach (var p in pdfByteContent) { //Create a PdfReader bound to that byte array using (var reader = new PdfReader(p)) { //Add the entire document instead of page-by-page copy.AddDocument(reader); } } doc.Close(); } } //Return just before disposing return ms.ToArray(); } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1252545.html

(0)
上一篇 2022年11月15日
下一篇 2022年11月15日

精彩推荐