问题描述
我正在尝试将多个PDF合并为单个PDF。PDF来自SSR,来自我处理过的一些本地报告。我正在使用PDFSharp,因为它已经在整个项目中使用了。但是,outputDocument.addPage(page)
方法抛出InvalidOperationException("Cannot change document.")
异常。我试过很多不同的方法,但都不能奏效.
这里是我的方法,其中所有输入都已经检查过:
private static void saveFile(string fileName, params byte[][] bytes)
{
try
{
PdfDocument outputDocument = new PdfDocument();
for (int i = 0; i < bytes.Length; i++)
{
using (MemoryStream stream = new MemoryStream(bytes[i]))
{
PdfDocument inputDocument = PdfReader.Open(stream, PdfDocumentOpenMode.Import);
foreach (PdfPage page in inputDocument.Pages)
{
outputDocument.AddPage(page); //throws the exception !!!
}
}
}
outputDocument.Save(fileName);
}
catch (Exception ex)
{
throw new Exception("Erreur lors de l'enregistrement du fichier", ex);
}
}
从我在网上看到的例子看,这似乎是做这件事的正确方式……我对合并PDF的其他建议持开放态度,但我不愿使用其他第三方库,如ITextSharp,因为项目中已经使用了PDFSharp。
如果重要的话,我在Win7计算机上使用VS2010 Pro。
编辑:异常中的调用堆栈:
at PdfSharp.Pdf.PdfObject.set_Document(PdfDocument value)
at PdfSharp.Pdf.PdfObject.ImportClosure(PdfImportedObjectTable importedObjectTable, PdfDocument owner, PdfObject externalObject)
at PdfSharp.Pdf.PdfPages.CloneElement(PdfPage page, PdfPage importPage, String key, Boolean deepcopy)
at PdfSharp.Pdf.PdfPages.ImportExternalPage(PdfPage importPage)
at PdfSharp.Pdf.PdfPages.Insert(Int32 index, PdfPage page)
at PdfSharp.Pdf.PdfPages.Add(PdfPage page)
at PdfSharp.Pdf.PdfDocument.AddPage(PdfPage page)
at Something.saveFile(String fileName, Byte[][] bytes)
问题出在我身上吗?这不是应该这样做的吗?或者,是否有其他方法可以将多个LocalReport合并为单个PDF?
推荐答案
我开始相信可能是输入的PDF已损坏或无法读取。有几个SSRS PDF不能被PDF库甚至Adobe的Reader读取的例子。例如:
..。这里:
https://stackoverflow.com/questions/2393175/ssrs-2008-pdf-files-cannot-be-opened
..。最重要的是在PDFSharp论坛上:
http://forum.pdfsharp.net/viewtopic.php?f=2&t=674
我不知道这是否是您遇到的错误-消息很奇怪-但它似乎与此有关,因为考虑到您的代码示例可以完美地与我尝试的任何PDF配合使用(不过,我没有任何SQL Server报告可供试用)
这篇关于使用PDFSharp合并多个PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!