C#iTextSharp通过字节数组合并多个pdf [英] C# iTextSharp Merge multiple pdf via byte array
问题描述
我是新手使用iTextSharp并且一般使用Pdf文件,但我认为我走在正确的轨道上。
I am new to using iTextSharp and working with Pdf files in general, but I think I'm on the right track.
我遍历pdf文件列表,将它们转换为字节,并将所有生成的字节推送到字节数组中。从那里我将字节数组传递给concatAndAddContent()以将所有pdf合并为单个大型pdf。目前我刚刚获得列表中的最后一个pdf(它们似乎被覆盖)
I iterate through a list of pdf files, convert them to bytes, and push all of the resulting bytes into a byte array. From there I pass the byte array to concatAndAddContent() to merge all of the pdf's into a single large pdf. Currently I'm just getting the last pdf in the list (they seem to be overwriting)
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的工作代码,以及其余的文件被忽略了。任何建议
Above is the working code that results in a single pdf being created, and the rest of the files are being ignored. Any suggestions
推荐答案
这几乎只是 Bruno的代码在这里。
这是合并PDF文件的最简单,最安全和最推荐的方法。 PdfSmartCopy
对象能够检测多个文件中的冗余,这可能会减少文件大小一些时间。其中一个重载接受一个完整的 PdfReader
对象,可以根据需要实例化。
This is pretty much the simplest, safest and recommended way to merge PDF files. The PdfSmartCopy
object is able to detect redundancies in the multiple files which can reduce file size some times. One of the overloads on it accepts a full PdfReader
object which can be instantiated however you want.
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();
}
}
这篇关于C#iTextSharp通过字节数组合并多个pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!