iTextSharp exception: PDF header signature not found

I found it was because I was calling new PdfReader(pdf) with the PDF stream position at the end of the file. By setting the position to zero it resolved the issue.

Before:

// Throws: InvalidPdfException: PDF header signature not found.
var pdfReader = new PdfReader(pdf);

After:

// Works correctly.
pdf.Position = 0;
var pdfReader = new PdfReader(pdf);

After some research, I've found that this problem relates to either a file being corrupted during PDF generation, or an error related to an object in the document that doesn't conform to the PDF standard as implemented in iTextSharp. It also seems to happen only when you read from a PDF file from disk.

I have not found a complete solution to the problem, but only a workaround. What I've done is read the PDF document using the PdfReader itextsharp object and see if an error or exception happens before reading the file in a normal operation.

So running something similar to this:

private bool IsValidPdf(string filepath)
{
    bool Ret = true;

    PdfReader reader = null;

    try
    {
        reader = new PdfReader(filepath);
    }
    catch
    {
        Ret = false;
    }

    return Ret;
}

Tags:

C#

.Net

Pdf

Itext