iTextSharp - Adobe Acrobat "save changes" prompt

I've been using iTextSharp on a couple of projects recently - it's a brilliant tool for producing dynamic PDF documents programmatically as part of your C# application.

However, users were reporting that when they opened the iTextSharp generated PDF files in Adobe Acrobat, on closing the document, they were receiving a prompt asking if they wanted to save changes.

Turns out this is connected with the way I was outputting the final PDF document to the browser.

When your code has finished generating an iTextSharp PDF document, you end up with a MemoryStream object which contains the PDF data ready for saving or output. To send this MemoryStream to the browser, I had been doing this:

Response.BinaryWrite(pdfMemoryStream.GetBuffer());

However, it seems that if you do this, you end up also appending a lot of whitespace/padding to the end of the download. This not only causes the issue with Adobe Acrobat asking if you want to save changes, but also causes the PDF file you generate to be much larger than necessary. The trick is this:

byte[] pdfBytes = pdfMemoryStream.ToArray();
Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);

Job done - a smaller file download and no more issues with opening/closing the file in Adobe Acrobat reader.

Comments