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");
Response.BinaryWrite(combinedContents);
Response.End();

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!

Advertisements

Actions

Information

21 responses

5 07 2010
saravanakumar.r

Hi

I have combined the bytes , after writing in response, i got Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

6 07 2010
Sarah

Hi there,

If you can give me some more information on what part is causing the problem and maybe a sample of your code, I can try and help. You’re welcome to email it to me if you’d prefer at sarahoutofhours@live.com.

If you’ve already fixed it (apologies for the delayed reply, I was on holiday!) then I’d be interested to know what the problem was.

Thanks,
Sarah

13 07 2010
Richa

Hi there,

i want to attach 2 pdf documents in one pdf
how can I achieve this.

13 07 2010
Sarah

Hi Richa,

I personally choose to use a tool called PDFSharp/MigraDoc. It is a free open source tool for creating PDF’s in .NET. If you go to their website, http://www.pdfsharp.net/ you can download it. You then open the projects and compile them to give you the required DLL’s. When you have these PDFSharp DLL’s, you can add them to your project in which you are trying to combine the PDF documents. That will then give you access to the objects and methods I use in my code sample.

Basically what I do in my code sample is create 3 PDFDocument objects. One for each PDF you want in your combined PDF, and then one for the combined PDF. I then loop through each PDF, adding each page into the new combined PDF.

If you are going to get PDFSharp, I would recommend getting to know your way around it a little. They have really good resources on their site, like a wiki with lots of examples. If you do a few of those, you will probably find the code in my sample pretty straightforward. Note that I was doing this for a web project, hence why I am saving the new PDF to a stream so that it can be opened on the client side. You may not need to anything more than save the file to the local file system.

I hope this helps, if you need anymore help just comment here or e-mail me at sarahoutofhours@live.com.

Thanks,
Sarah

27 07 2010
banshareef

Hi,
Can I use PDFSharp/MigraDoc to export asp.net page content to PDF ? if yes please give me example
Thanks

27 07 2010
Sarah

Hi,

It should definitely be possible to do this. If your page content is all in tags such as <asp:Label ID=”lblContent” runat=”server”>Content in here</asp:Label> then you can reference these from your C# code to add the lblContent.Text to your MigraDoc document. There may be an easier way though, I’ve never done it from an asp page myself. I always found their forum very helpful. The guys that code the libraries monitor it and often answer within a few hours. I might be able to help a bit more, if you can send me some examples of your code to sarahoutofhours@live.com I can take a look and let you know if I come up with any other ideas.

Thanks,
Sarah

2 12 2010
John Nguyen

Sarah,

thanks for the great post but I’m having trouble getting PdfReader.Open & PdfDocumentOpenMode , what assembly do I need to import?
I’m currently using PdfSharp; PdfSharp.Pdf; & PdfSharp.Drawings;

Thanks

2 12 2010
John Nguyen

Disregard, I figured it out. I’m sure I’ll have some more questions to add soon.

2 12 2010
Sarah

I was going to suggest using PdfSharp.Pdf.IO; 🙂 Is that what it was by any chance?

2 12 2010
John Nguyen

yes!

2 12 2010
John Nguyen

Sarah,

OK I’ve run into a problem trying to combine 2 ReportDocument (CR) using your sample. Can you help me out? You want me to type code here?

Thanks

2 12 2010
Sarah

Hi John,
You can post it here or you can e-mail it to sarah@usefulaspandcsharp.co.uk if you’d prefer that.
Thanks,
Sarah

2 12 2010
John Nguyen

Sarah,

Sorry I figured it out, type 🙂 !!! Thanks again for the post and quick help!

2 12 2010
John Nguyen

edit ^^ typo… :-)!

3 12 2010
Richa

Thanks Sarah for the great and timely help.
You r so punctual in ur replies.Thanks 🙂

4 02 2011
Aveshan

Hi Sarah How Can I Use PDFSharp to combine PDF’S that are stored on my computer in one single PDF. I Have tried everything its just not working

17 02 2011
Sarah

Hi Aveshan,

Apologies for my delay in replying (I’m about to put a new post up to explain why it’s a delayed reply!)

Are you still having this problem? If so I can take a look into it and see if I can do anything to help.

Thanks,
Sarah

23 04 2012
mleyzaola

Excellent, simply brillant. Your post has saved me a lot of hours since I needed to merge a bunch of reports for email distribution.
Have worked on a prove of concept with 10 already, everything looks cool.
Thanks!

17 10 2012
Gurneet

Hi Sara,
I have a pdf file saved in the database. I have a second pdf file that i am creating on the fly using the MigraDoc and then saving it to a byte array. Now the problem is when i try to get that saved pdf file and then try to merge with the newly created pdf, I get the following error.

“Cannot handle iref streams. The current implementation of PDFsharp cannot handle this PDF feature introduced with Acrobat 6.”

I know one solution to this is to save the pdf file in the database using Acrobat 5. But i cannot go with that because the file has to be uploaded by the client and we cannot ask him to use Acrobat 5.

Do you have any solution to this?

Thanks,
Gurneet

19 11 2012
Sarah

Hi Gurneet,

Very sorry about the delay in replying to this. Did you manage to figure this one out? If not let me know and I will give you my e-mail address so you can send me some more information and I will try and help you out.

Thanks,
Sarah

16 01 2015
Louise Eggleton

Awesome, works great. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: