Home » Tutorials » How to Protect PDF File with Password in Python

How to Protect PDF File with Password in Python

Are you worried about keeping your PDF files safe and secure? In today’s digital world, where documents are shared and accessed across various platforms, safeguarding your sensitive information is more crucial than ever.

Today, you’ll learn how to protect a PDF file with a password in Python. Let’s dive into using the tkinter GUI toolkit and the PyPDF2 library; it’s going to be simpler than you think! I’ll walk you through each step so you can confidently secure your documents. By the end of our time together, you’ll know how to create password-protected PDF files that keep your private information just that, private and safe from prying eyes.

Let’s get started!

Table of Contents

Necessary Libraries

Make sure to install these libraries via the terminal or your command prompt for the code to function properly:

$ pip install tk 
$ pip install PyPDF2

Imports

Since we intend for our program to be user-friendly, we import the tkinter library as tk to create a graphical user interface. From tkinter, we specifically import the filedialog module for selecting files and directories, the simpledialog module to provide a box for entering passwords, and the messagebox module for displaying message boxes.

Additionally, we import the PyPDF2 library, which enables us to work with PDF files.

import tkinter as tk
from tkinter import filedialog, simpledialog, messagebox
import PyPDF2

Protect PDF File Functions

Now, let’s define the heart of our Script:

select_pdf Function

This function starts by declaring file_path as a global variable, which stores the path of the selected PDF file and allows it to be accessed by other parts of the code. It uses filedialog.askopenfilename() to open a file dialog window, where it restricts the display to only PDF files using the filetypes option.

Once a user selects a PDF, the function updates status_label.config() to show the selected PDF and its path in blue on the main window, and it enables the lock button so it can be pressed. If no PDF file is selected, status_label.config() displays a “No file selected” message in red on the GUI.

def select_pdf():
   global file_path
   file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
   if file_path:
       status_label.config(text="PDF selected: " + file_path, fg="blue")
       lock_button.config(state=tk.NORMAL)
   else:
       status_label.config(text="No file selected", fg="red")

lock_pdf Function

When you trigger the lock_pdf function, it starts by asking you for a password through a dialog box, where your input remains hidden behind asterisks to ensure privacy. If you input a password, here’s what happens next: the function opens your chosen PDF file in read-binary (‘rb’) mode. This mode allows the function to read the file exactly as it is, down to every byte, ensuring no data is lost or altered in the process.

Next, the function sets up a new PDF “writer” to create a brand-new document. It then loops through all the pages in your original PDF, adding each one to this new document. Once all the pages are in place, it secures the document with the password you provided.

Here comes the exciting part: the function saves this newly created, password-protected PDF under a new name, appending “_locked” to the original filename to make it easy to identify. If everything goes smoothly, a pop-up message lets you know your PDF is now locked and secure. But, if something goes wrong during the process, you’ll get an error message detailing what happened. And if you decide not to enter a password, it’ll simply remind you that you need one to lock the PDF.

def lock_pdf():
   password = simpledialog.askstring("Password", "Enter a password to lock the PDF:", show="*")
   if password:
       try:
           with open(file_path, 'rb') as file:
               pdf_reader = PyPDF2.PdfReader(file)
               pdf_writer = PyPDF2.PdfWriter()
               for page in pdf_reader.pages:
                   pdf_writer.add_page(page)
               pdf_writer.encrypt(password)
               output_path = file_path[:-4] + "_locked.pdf"
               with open(output_path, 'wb') as output_file:
                   pdf_writer.write(output_file)
           messagebox.showinfo("Success", "PDF has been locked successfully!")
       except Exception as e:
           messagebox.showerror("Error", str(e))
   else:
       messagebox.showwarning("Warning", "No password entered. PDF not locked.")

Creating the Main Window

Following that, we create the main window, set its title, define its geometry, and make it non-resizable.

root = tk.Tk()
root.title("PDF Locker - The Pycodes")
root.geometry("400x200")
root.resizable(False,False)

Creating the GUI Elements

For this step, we start by creating a label that asks the user to select a PDF file. Next, we create a button labeled “Select PDF” that triggers the select_pdf() function when pressed. After that, we create another button labeled “Lock PDF”; this one starts out disabled and triggers the lock_pdf() function when clicked.

Finally, we create a status label that provides feedback on whether a PDF file has been selected.

# Create a label
label = tk.Label(root, text="Choose a PDF file to lock:")
label.pack(pady=10)


# Create a "Select PDF" button
select_button = tk.Button(root, text="Select PDF", command=select_pdf)
select_button.pack()


# Create a "Lock PDF" button
lock_button = tk.Button(root, text="Lock PDF", command=lock_pdf, state=tk.DISABLED)
lock_button.pack(pady=10)


# Status label
status_label = tk.Label(root, text="", fg="red")
status_label.pack(pady=10)

Initializing the file_path and Running the Main Loop

Lastly, we initialize the file_path variable to store the path of the selected PDF file. We then start the main event loop to ensure that the main window remains running and responsive to user interactions until it is exited willingly.

file_path = ""

root.mainloop()

Example

Full Code

import tkinter as tk
from tkinter import filedialog, simpledialog, messagebox
import PyPDF2


def select_pdf():
   global file_path
   file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
   if file_path:
       status_label.config(text="PDF selected: " + file_path, fg="blue")
       lock_button.config(state=tk.NORMAL)
   else:
       status_label.config(text="No file selected", fg="red")


def lock_pdf():
   password = simpledialog.askstring("Password", "Enter a password to lock the PDF:", show="*")
   if password:
       try:
           with open(file_path, 'rb') as file:
               pdf_reader = PyPDF2.PdfReader(file)
               pdf_writer = PyPDF2.PdfWriter()
               for page in pdf_reader.pages:
                   pdf_writer.add_page(page)
               pdf_writer.encrypt(password)
               output_path = file_path[:-4] + "_locked.pdf"
               with open(output_path, 'wb') as output_file:
                   pdf_writer.write(output_file)
           messagebox.showinfo("Success", "PDF has been locked successfully!")
       except Exception as e:
           messagebox.showerror("Error", str(e))
   else:
       messagebox.showwarning("Warning", "No password entered. PDF not locked.")


root = tk.Tk()
root.title("PDF Locker - The Pycodes")
root.geometry("400x200")
root.resizable(False,False)


# Create a label
label = tk.Label(root, text="Choose a PDF file to lock:")
label.pack(pady=10)


# Create a "Select PDF" button
select_button = tk.Button(root, text="Select PDF", command=select_pdf)
select_button.pack()


# Create a "Lock PDF" button
lock_button = tk.Button(root, text="Lock PDF", command=lock_pdf, state=tk.DISABLED)
lock_button.pack(pady=10)


# Status label
status_label = tk.Label(root, text="", fg="red")
status_label.pack(pady=10)


file_path = ""


root.mainloop()

Happy Coding!

Learn more about Python PDF Tutorials here.

Leave a Comment

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

Scroll to Top