我有两个Document
对象
如何Document
使用 itextsharp 合并这两个对象?
根据 Haas 先生(借助他在 SO 上的代码),
“不幸的是,据我所知,没有办法合并两个 Document 对象。这些对象是帮助类,抽象出 PDF 文件格式的复杂性。这些抽象的“成本”之一是你是有限的到单个文档。但是,正如其他人指出的那样,您可以创建单独的 PDF(甚至在内存中)然后合并它们。
所以我这样做了:
我使用了 PdfCopyFields 对象。
MemoryStream realfinalStream = new MemoryStream();
MemoryStream[] realstreams = { stream,new MemoryStream(finalStream.ToArray()) };
using (realfinalStream)
{
//Create our copy object
PdfCopyFields copy = new PdfCopyFields(realfinalStream);
//Loop through each MemoryStream
foreach (MemoryStream ms in realstreams)
{
//Reset the position back to zero
ms.Position = 0;
//Add it to the copy object
copy.AddDocument(new PdfReader(ms));
//Clean up
ms.Dispose();
}
//Close the copy object
copy.Close();
}
return File(new MemoryStream(realfinalStream.ToArray()), "application/pdf","hello.pdf");
供参考
new MemoryStream(realfinalStream.ToArray())
我这样做是因为 MemoryString 已关闭。
口感更轻松:
您必须获取 PDF 文档内存流并将它们合并在一起!
这是一个简单的函数来完成这个!
public MemoryStream MemoryStreamMerger(List<MemoryStream> streams)
{
MemoryStream OurFinalReturnedMemoryStream;
using (OurFinalReturnedMemoryStream = new MemoryStream())
{
//Create our copy object
PdfCopyFields copy = new PdfCopyFields(OurFinalReturnedMemoryStream);
//Loop through each MemoryStream
foreach (MemoryStream ms in streams)
{
//Reset the position back to zero
ms.Position = 0;
//Add it to the copy object
copy.AddDocument(new PdfReader(ms));
//Clean up
ms.Dispose();
}
//Close the copy object
copy.Close();
//Get the raw bytes to save to disk
//bytes = finalStream.ToArray();
}
return new MemoryStream(OurFinalReturnedMemoryStream.ToArray());
}