How to encrypt PDF as Password Protected File in Python

Here I am going to show you an example how to encrypt PDF to make it password protected using PyPDF2 module in Python programming language. I am not going to show you how to create a new PDF file in this example and I am going to read the existing PDF file and making this PDF file password protected.

It is a good idea to make the PDF password protected when you want to send some sensitive data into the PDF file over the network, such as, email or you are allowing end users to download the PDF files.

Prerequisites

Python 3.9.1, PyPDF2

Install PyPDF2

If you do not have PyPDF2 installed on your system then you can install it using the command pip install pypdf2 as shown in the following image:

password protected pdf in python

Encrypt PDF File

Here I am going to show you how to make PDF password protected. I am going to use the same PDF file which got generated using FPDF module in Python.

At first I am going to read the PDF file going to make it password protected. Finally writing to the output PDF file. When you open the PDF file, it will ask for password. And you can input password for opening the file.

import PyPDF2

pdf_in_file = open("simple.pdf",'rb')

inputpdf = PyPDF2.PdfFileReader(pdf_in_file)
pages_no = inputpdf.numPages

for i in range(pages_no):
	inputpdf = PyPDF2.PdfFileReader(pdf_in_file)
	
	output = PyPDF2.PdfFileWriter()
    
	output.addPage(inputpdf.getPage(i))
	output.encrypt('password')

	with open("simple_password_protected.pdf", "wb") as outputStream:
		output.write(outputStream)

pdf_in_file.close()

The important function in the above code is encrypt() that accepts password which will be later used to open the PDF file.

encrypt(user_pwd, owner_pwd=None, use_128bit=True)

Where,

user_pwd (str) – The user password, which allows for opening and reading the PDF file with the restrictions provided.
owner_pwd (str) – The owner password, which allows for opening the PDF files without any restrictions. By default, the owner password is the same as the user password.
use_128bit (bool) – flag as to whether to use 128bit encryption. When false, 40bit encryption will be used. By default, this flag is on.

Testing the App

Running the above Python code you will see simple_password_protected.pdf file gets generated in the same folder where your Python script is stored.

When you try to open the file you will be asked for the password:

password protected pdf in python

Now you can type password in the input box to open the content in the file.

That’s all about how to make PDF file password protected.

Source Code

Download

Leave a Comment