9

Possible Duplicate:
Detect if PDF file is correct (header PDF)

I want to validate that the data in a FileStream instance represents a valid PDF document. Specifically, I need to know that Adobe Reader will be able to successfully open the file.

Can anyone recommend an open source library or best practice for this task?

Community
  • 1
  • 1
smartcaveman
  • 41,281
  • 29
  • 127
  • 212
  • Write it to a file, and try to open using the default application. Don't know what to do when there is no application associated with `.pdf` though :) – khachik Jan 11 '12 at 14:35
  • I don't think it's possible other than opening it up with adobe reader. I'm interested to see if there is a another way. – Jason Meckley Jan 11 '12 at 14:40
  • https://stackoverflow.com/a/3257743/2778651 is the answer . First 4 bytes should give the answer – makdu Nov 13 '19 at 00:30

2 Answers2

18

Take a look at iTextSharp , it should give you what you need.

EDIT:

I know it's bad practice to use exceptions to control flow, but you could do this:

public bool IsValidPdf(string fileName)
{
   try
   {
      new iTextSharp.text.pdf.PdfReader(fileName);
      return true;
   }
   catch (iTextSharp.text.exceptions.InvalidPdfException)
   {
      return false;
   }
}
Myles McDonnell
  • 12,943
  • 17
  • 66
  • 116
  • Do you know how to accomplish this with iTextSharp? It turned up in my research, but [this blog](http://jeffgermain.wordpress.com/2009/12/22/validating-pdf-documents/) said that iTextSharp has no such feature – smartcaveman Jan 11 '12 at 14:37
  • I just assumed it did, I take a look, been a while since I used it.. – Myles McDonnell Jan 11 '12 at 14:45
-2

Open the file in memory and check if the first line is something like:

%PDF-1.5

or

%PDF-1.4

or simple %PDF string.

it's not very secure but worked for me.

Gustavo F
  • 2,071
  • 13
  • 23
  • 1
    Most likely downvoted due to the fact that question is whether the filestream is a PDF not thinks it is a PDF. The existence of that first line does not guarantee that it is a PDF. – fkm71 May 26 '21 at 18:54