password protect pdf file in python

How to Password Protect PDF in Python

Python is a powerful language that allows you to work with files & data. Sometimes you may need to password protect PDF documents using Python, as a part of your application or website. There are many python modules available for this purpose. Here are the steps to password protect PDF in Python.


How to Password Protect PDF in Python

Here are the steps to password protect PDF in python.

You can use PyPDF2 for this purpose.

Here is the command to install it on your system.

$ pip3 install PyPDF2

Let us say you want to convert input.pdf file to password-protected output.pdf file. If you want to password protect the same file then overwrite the input file with output file after password protection.

Here is the code snippet for this purpose.

from pyPDF2 import PdfFileReader, PdfFileWriter
with open("input.pdf", "rb") as in_file:
    input_pdf = PdfFileReader(in_file)

output_pdf = PdfFileWriter()
output_pdf.appendPagesFromReader(input_pdf)
output_pdf.encrypt("password")

with open("output.pdf", "wb") as out_file:
        output_pdf.write(out_file)

In the above example, we open input.pdf for reading. Then we create an instance of PdfFileWriter and call appendPagesFromReader() to create a new PDF file. Then we call encrypt() function to encrypt it. Replace ‘password’ with the password you would like to use for encryption. You can also encrypt the input file as-is without creating a separate password-protected file. By default, it uses 128-bit encryption.

You can decrypt the file using decrypt function.

from PyPDF2 import PdfFileWriter, PdfFileReader

with open("output.pdf", "rb") as in_file:
    input_pdf = PdfFileReader(in_file)

output_pdf = PdfFileWriter()
output_pdf.appendPagesFromReader(input_pdf)
output_pdf.decrypt("password")

with open("decrypt-output.pdf", "wb") as out_file:
        output_pdf.write(out_file)

In this case, we basically reverse the process. We open the output.pdf file for reading and then call decrypt() function to decrypt the file to decrypt-output.pdf. You need to provide the same password that was used to encrypt the file previously.

Here is the detailed documentation about PyPDF2.

Please note, starting version 1.26.0 the package is called PyPDF2 instead of pyPDF2. So if you are using version < 1.26.0 you need to use pyPDF2 in import statement.

from pyPDF2 import PdfFileWriter, PdfFileReader

In this article, we have learnt how to encrypt as well as decrypt PDF files using Python.

Also read:

How to Read Inputs as Numbers in Python
How to Split List into Even-sized Chunks in Python
How to Fix Temporary Failure in Name Resolution Issue in Linux
How to Add Route in Linux
How to Change Root Password in CentOS, RHEL, Fedora

Leave a Reply

Your email address will not be published. Required fields are marked *