How to Lock PDFs in Python

Discover how to utilize the PyPDF2 library to password-protect and encrypt PDF files, ensuring top-notch security for sensitive documents. Learn to create a secure PDF locker and adopt strong password practices for enhanced cybersecurity.
  · 5 min read · Updated feb 2024 · Ethical Hacking · PDF File Handling · Cryptography

Juggling between coding languages? Let our Code Converter help. Your one-stop solution for language conversion. Start now!

In this tutorial, we’re going to be building a PDF locker. A PDF, or Portable Document Format, is a file format developed by Adobe that preserves the formatting and layout of a document, regardless of the software, hardware, or operating system used to view or print it. PDF files can contain text, images, links, and interactive elements, making them a versatile format for sharing documents. 

PDFs are widely used for various purposes, such as sharing business reports, eBooks, forms, and academic papers. They are also commonly used for distributing documents that need to be printed exactly as intended. PDFs can be viewed and edited using various software applications, including Adobe Acrobat Reader, a free and widely used PDF viewer.

Sometimes we might have confidential information saved in PDFs, and we wouldn’t want Tom, Dick and Harry to access it. One of the options we have is to password-protect our files. Another option is obviously encrypting the file. But because we like variety, we will see another method of keeping our files away from unwanted eyes. I’m sure you agree that this program's importance cannot be overemphasized. 

For this program, we’ll be making use of PyPDF2 for PDF manipulations, such as reading and setting passwords to the PDF.

To install:

$ pip install PyPDF2 colorama

Then as usual, we create a Python file. Name it meaningfully, like

Getting to the code, we start by importing the necessary libraries:

# Import the necessary libraries
import PyPDF2, getpass # getpass is for getting password with some level of security
from colorama import Fore, init

# Initialize colorama for colored output

getpass is used to get a user's password with some level of security, such that when a user enters their password in public places, their password is not displayed on the screen.

Next, we create a function that does the PDF-locking:

# Function to lock pdf
def lock_pdf(input_file, password):
   with open(input_file, 'rb') as file:
       # Create a PDF reader object
       pdf_reader = PyPDF2.PdfReader(file)
       # Create a PDF writer object
       pdf_writer = PyPDF2.PdfWriter()
       # Add all pages to the writer
       for page_num in range(len(pdf_reader.pages)):
       # Encrypt the PDF with the provided password
       # Write the encrypted content back to the original file
       with open(input_file, 'wb') as output_file:

Finally, we collect the user’s input:

# Get user input
input_pdf = input("Enter the path to the PDF file: ")
password = getpass.getpass("Enter the password to lock the PDF: ")

# Lock the PDF using PyPDF2
print(f'{Fore.GREEN}[!] Please hold on for a few seconds..')
lock_pdf(input_pdf, password)

# Let the user know it's done
print(f"{Fore.GREEN}[+] PDF locked successfully.")

That’s essentially it. To run our code, make sure to have a PDF to test in your directory or specify the full PATH to the PDF file. 

Before you run this code, please store your password in a secure location or use a password manager. For testing purposes, It’s highly recommended to create a copy of the PDF file you want to test with so that in case you unwittingly mess things up, you will still have a backup. 

I’m testing my code with my copy of the Ethical-Hacking-With-Python.pdf eBook. Feel free to use any PDF of your choice while factoring all considerations:

$ python
Enter the path to the PDF file: Ethical-Hacking-With-Python.pdf
Enter the password to lock the PDF:
[!] Please hold on for a few seconds..
[+] PDF locked successfully.

When I try to open the PDF now:

Now, no one can open our file without the password. However, it’s good to note that if you forget your password to lock your file, you may lose access to it permanently. Unlike online applications, you can easily request a new password by hitting the Forgot password button. So please store your passwords by either writing them down and keeping them very safe or using a password manager. Similar to what we built here.

Also, if you want to learn how to crack locked PDFs, check this tutorial out.

Using a strong password is crucial as it serves as the first line of defense against unauthorized access, significantly enhancing the security of your accounts and sensitive information. So please be sure to use a strong password. Check this tutorial to generate passwords with Python.

Finally, Diving into the practicalities of securing PDFs in Python opens a glimpse into the broader universe of cybersecurity and programming. If this tutorial sparked your interest and you're keen on furthering your journey into the realms of digital security and encryption, our Cryptography with Python eBook is the perfect next step. It's designed to broaden your horizons with a richer, more detailed exploration of cryptographic concepts and their implementation in Python, offering you a path to elevate your skills and knowledge in this critical and fascinating domain.

Happy coding ♥

Let our Code Converter simplify your multi-language projects. It's like having a coding translator at your fingertips. Don't miss out!

View Full Code Explain The Code for Me
Sharing is caring!

Read Also

Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!