Combining 2 PDF Documents into 1 with PDFSharp

4 03 2010

After looking at the example of how to do this on the PDF sharp website, I wrote the following code to combine 2 existing PDF documents into one & send the new document back to the user to download. Both PDF documents existed as byte arrays (which I had retrieved from my database, reportPdfContents & certsPdfContents) so if you’re retrieving them from your file system, you will need to slightly alter the code.

MemoryStream msReport = new MemoryStream(reportPdfContents); //reportPdfContents is a byte array
MemoryStream msCerts = new MemoryStream(certsPdfContents); //certsPdfContents is a byte array
PdfDocument reports = PdfReader.Open(msReport, PdfDocumentOpenMode.Import);
PdfDocument certificates = PdfReader.Open(msCerts, PdfDocumentOpenMode.Import);
PdfDocument combinedOutput = new PdfDocument();
int repPageCount = reports.PageCount;
for (int i = 0; i < repPageCount; i++)
PdfPage page = reports.Pages[i];
page = combinedOutput.AddPage(page);
int certPageCount = certificates.PageCount;
for (int i = 0; i < certPageCount; i++)
PdfPage page = certificates.Pages[i];
page = combinedOutput.AddPage(page);
byte[] combinedContents = null;
using(MemoryStream stream = new MemoryStream())
combinedOutput.Save(stream, true);
combinedContents = stream.ToArray();
Response.ContentType = "application/pdf"; //set the MIME type here
Response.AddHeader("content-disposition", "attachment; filename=ReportAndCertificates.pdf");

If you are familiar with PDF Sharp and have already looked at the examples, I think this code is probably pretty self explanatory. If you want some more information though, on the PDF’s, saving to/reading from byte arrays or opening a file on the client side just leave a comment. I do check them quite often so I’ll probably reply fairly quickly!