The problem with using the PdfReader.IsEncrypted
method is that if you attempt to instantiate a PdfReader
on a PDF that requires a password - and you don't supply that password - you'll get a BadPasswordException
.
Keeping this in mind you can write a method like this:
public static bool IsPasswordProtected(string pdfFullname) {
try {
PdfReader pdfReader = new PdfReader(pdfFullname);
return false;
} catch (BadPasswordException) {
return true;
}
}
Note that if you supply an invalid password you'll get the same BadPasswordException
when attempting to construct a PdfReader
object. You can use this to create a method that validates a PDF's password:
public static bool IsPasswordValid(string pdfFullname, byte[] password) {
try {
PdfReader pdfReader = new PdfReader(pdfFullname, password);
return false;
} catch (BadPasswordException) {
return true;
}
}
Sure it's ugly but as far as I know this is the only way to check if a PDF is password protected. Hopefully someone will suggest a better solution.