23

I have been using iTextSharp to generate PDF documents for over a year. Unfortunately, with the release of Adobe Reader X, my PDFs now cause a "Do you want to Save?" dialog to appear when closing the PDF document. This does not happen with PDFs that are not generated with iTextSharp. It's really annoying for my users who are opening and closing PDF documents all day long. Are there any properties in iTextSharp that I can set to prevent this from happening?

If it helps, I am using a PdfReader to read data from an existing PDF document (this original document does not cause the Save dialog to appear). I then use a PdfWriter to create a new document and AddTemplate to copy a portion of the original document to the new one.

Shog9
  • 156,901
  • 35
  • 231
  • 235
Jason
  • 233
  • 2
  • 4
  • I've actually been noticing this issue, too, so I'm curious if you find any answers. – Chris Haas Feb 25 '11 at 01:48
  • there are 2 possible causes: the document contains form fields and the AcroForm object has the NeedAppearances flag set to true or there is a bug in the PDF file, bug that was ignored in the previous versions of Adobe Reader. If you can post a link to a sample PDF file, I can take a look at it and give you more info. – iPDFdev Feb 25 '11 at 08:28

2 Answers2

28

The problem is this line:

Response.OutputStream.Write(MS.GetBuffer(), 0, MS.GetBuffer().Length)

The GetBuffer method returns the entire internal buffer which is larger that the actual content. The bad PDF has about 10kb of garbage content at the end (bytes of zero), the good PDF has only a few garbage bytes. Use the ToArray() method of the memory stream to get the PDF file and the problem will be fixed. You will also get smaller files.

byte[] pdf = MS.ToArray();
Response.OutputStream.Write(pdf, 0, pdf.Length);

Also set the "Content-Length" with the length of the pdf array.

iPDFdev
  • 5,229
  • 2
  • 17
  • 18
  • 1
    Well, you fixed my problem! Thanks @Sorin Nistor! I'm not even sure where I got this `GetBuffer()` code from, I usually use `ToArray()` which is why I only recently started noticing this problem. – Chris Haas Feb 25 '11 at 17:33
  • 1
    This fixed my problem too! It's weird - I usually use ToArray() as well, but all of my PDF code used GetBuffer(). It looks like many of the iTextSharp code samples on the web use GetBuffer, so I am sure I just copied some code. Hopefully this post will help others who start noticing this issue as well. @Sorin Nistor - thanks so much! @Chris Haas - thanks for posting your code. – Jason Feb 26 '11 at 04:34
  • 1
    I wish I could upvote this answer more than once. totally saved my time and sanity :) – kolin Nov 15 '13 at 09:29
1

Also add

HttpContext.Current.Response.End();

After completion of your PDF file.

Vandana
  • 161
  • 7