3

I'm writing an app in c# that fills a bunch of pdf forms, concatenates them then puts in some page numbers. I'm having difficulty with the memorystream result from the pdfstamper. If I change the memorystream to a filestream it works fine but I don't want to use the filesystem. I've created the following code snippet that reproduces my error:

    public static void TestStreams(string filepath)
    {
        PdfReader reader = new PdfReader(filepath);
        MemoryStream ms = new MemoryStream();
        PdfReader.unethicalreading = true;
        PdfStamper stamper = new PdfStamper(reader, ms);
        byte[] result = ms.ToArray();
        //The error is in the following line
        PdfReader reader2 = new PdfReader(result);
    }

The error is:

iTextSharp.text.exceptions.InvalidPdfException was unhandled
  HResult=-2146232800
  Message=Rebuild failed: trailer not found.; Original message: PDF startxref not found.
  Source=itextsharp

How can I fix it?

Maleki
  • 4,038
  • 1
  • 15
  • 17

1 Answers1

4

You forgot one line:

public static void TestStreams(string filepath) {
    PdfReader reader = new PdfReader(filepath);
    MemoryStream ms = new MemoryStream();
    PdfReader.unethicalreading = true;
    PdfStamper stamper = new PdfStamper(reader, ms);
    stamper.Close();
    byte[] result = ms.ToArray();
    //The error is in the following line
    PdfReader reader2 = new PdfReader(result);
}

When you do ms.ToArray() without first closing the stamper, you have an incomplete PDF. The PDF starts with %PDF-, but there's no %%EOF, no trailer, no catalog. An incomplete PDF can't be read by PdfReader.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • Works like a charm. Should have come to stackoverflow sooner. Thanks! – Maleki Apr 20 '16 at 13:50
  • @BrunoLowagie 2 years later, I stumbled upon this post as I was having the same issue as the OP. This fixed my problem as well. Thank you very much, +1 from me. – Ryan Wilson May 14 '18 at 18:21