Last active
October 29, 2015 12:36
-
-
Save Niels-V/33e36fe808890f5e7bb2 to your computer and use it in GitHub Desktop.
PDF Check in a filestream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/PDF32000_2008.pdf 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