1

I have a PDF I am trying to open up and alter slightly (just changing the ViewerPreferences) but can't seem to work out the exact usage of iTextSharp. The file that gets saved at the end is corrupt. Any ideas?

        PdfReader reader = new PdfReader(@"C:\4803.pdf");

        using (var stream = new MemoryStream())
        {
            PdfStamper stamper = new PdfStamper(reader, stream);
            stamper.ViewerPreferences = PdfWriter.AllowPrinting | PdfWriter.PrintScalingNone;

            stream.Position = 0;
            byte[] output = LoadFromStream(stream); // Convert it to a byte array
            SaveToFile(output, @"C:\4803_out.pdf"); // Save it to a file

            stamper.Close();
        }
Craig
  • 36,306
  • 34
  • 114
  • 197

1 Answers1

3

Close the PdfStamper before converting the MemoryStream to a byte array and saving it. The way you do it, the pdf is not yet completed in the stream.

PS: To prevent the closing of the stamper from also closing the stream, use

stamper.Writer.CloseStream = false
mkl
  • 90,588
  • 15
  • 125
  • 265
  • When I do that the stream is also closed which is not helpful for extracting the byte[] from it. – Craig Oct 26 '12 at 04:42
  • This actually doesn't give an error now but doesn't seem to apply the PdfWriter.PrintScalingNone preference. – Craig Oct 28 '12 at 10:21