[英]C# iTextSharp Merge multiple pdf via byte array
我刚开始使用 iTextSharp 和一般的 Pdf 文件,但我认为我走在正确的轨道上。
我遍历 pdf 文件列表,将它们转换为字节,然后将所有生成的字节推送到字节数组中。 从那里我将字节数组传递给 concatAndAddContent() 以将所有 pdf 合并为一个大的 pdf。 目前我只是得到列表中的最后一个 pdf(它们似乎被覆盖了)
public static byte[] concatAndAddContent(List<byte[]> 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
对象,可以根据需要进行实例化。
public static byte[] concatAndAddContent(List<byte[]> 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();
}
}
List<byte[]> branchWiseList = new List<byte[]>();
branchWiseList.Add(bytes); // add here byte array.
then call your function concatAndAddContent(branchWiseList);
System.IO.File.WriteAllBytes("path", concatAndAddContent(branchWiseList));
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.