I am trying to combine multiple PDFs into a single PDF. The PDFs come from SSRS, from some LocalReports that I processed. I am using PDFSharp, because it is already used through out the project. However, the outputDocument.addPage(page)
methods throws an InvalidOperationException("Cannot change document.")
exception. I have tried many different way of doing this, but I can't get it to work...
Here my method, where all the inputs have already been checked:
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);
}
}
From the examples I saw on the web, this seems to be the right way of doing this... I am opened to other suggestions for merging my PDFs, but I would rather not use another 3rd party lib, like ITextSharp, because PDFSharp is already used in the project.
If it matters, I am using VS2010 Pro on a Win7 machine.
EDIT : Call stack from the exception :
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)
Is the problem me? Isn't this the way this is supposed to be done? Or is there any other way of combining multiple LocalReport into a single PDF?