checking if pdf is password protected using itextsharp

21,995

Solution 1

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.

Solution 2

  private void CheckPdfProtection(string filePath)
        {
            try
            {
                PdfReader reader = new PdfReader(filePath);
                if (!reader.IsEncrypted()) return;
                if (!PdfEncryptor.IsPrintingAllowed(reader.Permissions))
                    throw new InvalidOperationException("the selected file is print protected and cannot be imported");
                if (!PdfEncryptor.IsModifyContentsAllowed(reader.Permissions))
                    throw new InvalidOperationException("the selected file is write protected and cannot be imported");
            }
            catch (BadPasswordException) { throw new InvalidOperationException("the selected file is password protected and cannot be imported"); }
            catch (BadPdfFormatException) { throw new InvalidDataException("the selected file is having invalid format and cannot be imported"); }
        }

Solution 3

Reference : Check for Full Permission

You should be able to just check the property PdfReader.IsOpenedWithFullPermissions.

PdfReader r = new PdfReader("YourFile.pdf");
if (r.IsOpenedWithFullPermissions)
{
    //Do something
}
Share:
21,995
Md Kamruzzaman Sarker
Author by

Md Kamruzzaman Sarker

Love to find new applications of deep learning and knowledge graph. Website

Updated on January 25, 2020

Comments

  • Md Kamruzzaman Sarker
    Md Kamruzzaman Sarker over 4 years

    I want to check if a pdf file is password protected or not to view. That is i want to know if the pdf file has user password or not.

    I found some help in some forum about it to use isencrypted function but it does not give correct answer.

    Is it possible to check if a pdf is password protected?