Skip to content

Instantly share code, notes, and snippets.



Last active Oct 29, 2015
What would you like to do?
PDF Check in a filestream
using System;
using System.IO;
using System.Text;
namespace Example
public class FileCheck
/// <summary>
/// Determines whether the specified file stream is a valid PDF.
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <returns><c>true</c> when the stream has a start and end according to the PDF specification; <c>false</c> otherwise.</returns>
/// <remarks>See for the PDF specification.
/// Also note that the check executed is quite generic.
/// </remarks>
internal static bool IsValidPdf(Stream fileStream)
if (fileStream.Length < 12)
return false; // as we cannot have both the header and the trailer contained in the file
fileStream.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[7];
fileStream.Read(buffer, 0, 5);
//PDF with BOMs are not valid
bool headerCorrect = Encoding.ASCII.GetString(buffer).StartsWith("%PDF-");
fileStream.Seek(-7, SeekOrigin.End);
fileStream.Read(buffer, 0, 7);
//Validate the last line is %%EOF with contains, as there can be line endings after the EOF, which can be \r or \n or both
bool trailerCorrect = Encoding.ASCII.GetString(buffer).Contains("%%EOF");
fileStream.Seek(0, SeekOrigin.Begin);
return headerCorrect && trailerCorrect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment