How to Decrypt a PDF File in Python



Python


In this article, we show how to decrypt a PDF file in Python.

Decrypting means that we are able to undo the encryption of a PDF file so that we can read it.

Without decrypting it, the file is basically useless.

When we decrypt it by providing a password to undo the encryption, we can making it readable and usable to humans.

So, as we explained encrypted PDF files need a password in order to decrypt it.

A third-party module that works well with PDFs is the PyPDF2 module. We will be using this module to decrypt PDF files.

We can provide this password to a PDF file in Python by the decrypt() function, passing in the password as the parameter to this function.

If you want to see if a PDF file is encrypted or not, you can use the isEncrypted attribute, which will return True or False.

This is shown below.



If the isEncrypted attribute is True, then the file is encrypted and will need to be decrypted in order to use. Below we have a PDF file, which we open and decrypt.



So the first thing we have to do is import the PyPDF2 module, which allows us to work with PDF files.

So we create a variable, pdffile, which accesses the pdf file, file1.pdf', in our current working directory.

We then create another variable, pdfreader, which is a PdfFileReader object which represents the file1.pdf. This allows us to work with PDF files with this module.

We then use the decrypt() function, passing in the password as a parameter, to unencrypt the PDF file, so that we can perform actions on the file such as read it.

An encrypted PDF file is really a password-protected file in which only people with the password can unlock it.

This can be done through a desktop software that handles PDF files through the software itself or it can be done through Python code such as that shown above.

Once you have used the decrypt() function in Python and it has returned a value of 1, then the file is now unlocked.

And this is how we can decrypt a PDF file in Python using the PyPDF2 module.


Related Resources

How to Create a Zip File in Python

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python



HTML Comment Box is loading comments...