Encrypt & Decrypt PDF Files using Python - Tkinter Project

encrypt and decrypt pdf files by password using python - PySeek

Introduction

Usually we humans apply various methods to protect our sensitive things (be it data or real life objects) from being stolen. For example, we set password for our computer system to prevent any unauthorized access just like we lock the main entrance of our premises.

In this tutorial, I will show you how you can Encrypt and Decrypt your PDF files with the help of Python language. A PDF or Portable Document Format is a file format that can hold a lot of data including text and image into it.

Since it is a very familiar file format used in the digital world, sometimes it becomes necessary to protect it to avoid unintended access. I have created an application that will Encrypt and Decrypt any PDF file with a Password.

I used two Python libraries to create this application. First, the Tkinter library is used to manage the user interface, and the PyPDF2 library is used to work with PDF files using Python.

At the end, we will convert the entire program into an executable file so that anyone can easily access it.

Requirements

Before you start writing your code just take a break here. Install these necessary libraries if you didn't already.

☛Install Tkinter: pip install tk

☛Install Pillow: pip install Pillow

☛Install PyPDF2: pip install PyPDF2

Import the Modules

Let's create a Python file with the name "Secure_PDF.py" and start writing your code by importing these modules.


import os
from tkinter import *
from functools import partial
from tkinter import filedialog, messagebox
from PyPDF2 import PdfFileReader, PdfFileWriter

Declare the 'En_Dec_rypt' class

Now declare this 'En_Dec_rypt' class. The name may seem a little bit weird to you. If so, you can choose another name(for this case you have to change the code a little bit in the main function; see the yellow marked line in the main function).


class En_Dec_rypt:

Declare the __init__() function

It will create a GUI window for us. We set the window size, title, resizable option, etc. here. Later we create a frame here and call the Home_Page() function.


def __init__(self, root):
# Setting the Tkinter main window
self.window = root
self.window.geometry("700x420")
self.window.title('Encrypt & Decrypt PDFs')
self.window.resizable(width = False, height = False)

# Creating a Frame
self.frame = Frame(self.window,bg="gray22",width=700,height=420)
self.frame.place(x=0, y=0)
# Calling the Home_Page() function
self.Home_Page()

Declare the Home Page

This function will display two buttons('Encrypt', and 'Decrypt') on the main window.


def Home_Page(self):
# Call the Clear Screen Function
self.ClearScreen()
# Encrypt Button
encrypt_button = Button(self.frame, text='Encrypt',\
font=("Helvetica", 18, 'bold'), bg="red", fg="white", width=7,\
command=partial(self.Open_File, 1))
encrypt_button.place(x=280, y=130)

# Decrypt Button
decrypt_button = Button(self.frame, text='Decrypt', \
font=("Helvetica", 18, 'bold'), bg="yellow", fg="black", \
width=7, command=partial(self.Open_File, 2))
decrypt_button.place(x=280, y=200)

Clear the Screen

This function clears all the widgets from the frame we declared in the __init__() function. It may seem widgets are vanishing from the main window; actually, there is the frame instead of the main window.


# Remove all widgets from the Home Page(self.frame)
def ClearScreen(self):
for widget in self.frame.winfo_children():
widget.destroy()

Select the PDF file

Tkinter offers to select a file from the system storage through the file dialog(a graphical interface that shows the directory and files present in the system storage). It reduces the headache of programming by choosing the file directly instead of mentioning every file path in the program.

This Open_File() function will let users select only one PDF file at once from the system storage.


# It opens a filedialog to select only one PDF file
# at once from the system storage
def Open_File(self, to_call):
self.PDF_path = filedialog.askopenfilename(initialdir = "/", \
title = "Select a PDF File", \
filetypes = (("PDF files", "*.pdf*"),))
if len(self.PDF_path) != 0:
if to_call == 1:
self.GetData_to_Encrypt()
else:
self.GetData_to_Decrypt()

Get necessary data to perform Encrypt Operation

This function will display the name of the selected PDF file, and the total page number, and take the password from the users(through the tkinter entry box) to encrypt the selected PDF file.

setting a password to a pdf file to encrypt it using this python application
Image - Setting password to a PDF File

# Get necessary data to perform the Encrypt operation
def GetData_to_Encrypt(self):
pdfReader = PdfFileReader(self.PDF_path)
total_pages = pdfReader.numPages

self.ClearScreen()
# Button for getting back to the Home Page
home_btn = Button(self.frame, text="Home", \
font=("Helvetica", 8, 'bold'), command=self.Home_Page)
home_btn.place(x=10, y=10)

# Header Label
header = Label(self.frame, text="Encrypt PDF", \
font=("Kokila", 25, "bold"), bg="gray22", fg="yellow")
header.place(x=250, y=15)

# Label for showing the total number of pages
pages_label = Label(self.frame, \
text=f"Total Number of Pages: {total_pages}", \
font=("Times New Roman", 18, 'bold'),bg="gray22",fg="white")
pages_label.place(x=40, y=90)

# Label for showing the filename
name_label = Label(self.frame, \
text=f"File Name: {os.path.basename(self.PDF_path)}", \
font=("Times New Roman", 18, 'bold'),bg="gray22",fg="white")
name_label.place(x=40, y=130)

# Set Password Label
set_password = Label(self.frame, \
text="Set Password: ", \
font=("Times New Roman", 18, 'bold'),bg="gray22",fg="white")
set_password.place(x=40, y=170)

# Entrybox to set the password to encrypt the PDF file
self.set_password = Entry(self.frame, \
font=("Helvetica, 12"), show='*')
self.set_password.place(x=190, y=174)

# Encrypt Button
Encrypt_btn = Button(self.frame, text="Encrypt", \
font=("Kokila", 10, "bold"), cursor="hand2", \
command=self.Encrypt_PDF)
Encrypt_btn.place(x=290, y=220)

Get necessary data to perform Decrypt Operation

This function will take the password from the users that they had chosen when encryption was done on that file.

unlocking a pdf file by password using this python application
Image - Unlocking a PDF File

# Get necessary data to perform the Decrypt operation
def GetData_to_Decrypt(self):
self.ClearScreen()
# Button for getting back to the Home Page
home_btn = Button(self.frame, text="Home", \
font=("Helvetica", 8, 'bold'), command=self.Home_Page)
home_btn.place(x=10, y=10)

# Header Label
header = Label(self.frame, text="Encrypt PDF", \
font=("Kokila", 25, "bold"), bg="gray22", fg="yellow")
header.place(x=250, y=15)

# Enter Password Label
enter_password = Label(self.frame, \
text="Enter Password: ", \
font=("Times New Roman", 18, 'bold'), bg="gray22", fg="white")
enter_password.place(x=40, y=170)

# Entrybox to get the password to decrypt the PDF file
self.ent_password = Entry(self.frame, \
font=("Helvetica, 12"), show='*')
self.ent_password.place(x=220, y=174)

# Decrypt Button
Decrypt_btn = Button(self.frame, text="Decrypt", \
font=("Kokila", 10, "bold"), cursor="hand2", \
command=self.Decrypt_PDF)
Decrypt_btn.place(x=290, y=220)

Perform the Encrypt Operation

Let's perform the Encryption operation on the selected PDF file. In this case, the Encrypted file will overwrite with the main file in the same location where it was situated. 

I've mentioned one comment line before each line of the code. It will help you to understand the objective of the code better.


# Function to perform Enryption Operation
def Encrypt_PDF(self):
if self.set_password.get() == '':
messagebox.showwarning('Warning', "Please set the password")
else:
try:
# Read the PDF file
pdfFile = PdfFileReader(self.PDF_path)
# Create a PdfFileWriter object
pdfWriter = PdfFileWriter()
# The Result file: Same name as the original
result = open(self.PDF_path, 'wb')

# Iterate through every pages of the PDF file
for page in range(pdfFile.getNumPages()):
# Add the page to the pdfWriter variable
pdfWriter.addPage(pdfFile.getPage(page))

# Encrypt the PDf file
pdfWriter.encrypt(user_pwd=self.set_password.get())
# Write the Result file
pdfWriter.write(result)
messagebox.showinfo('Done!',\
"The PDF file has been encrypted")
# Calling the Home_Page() function
self.Home_Page()
# Set the self.PDF_path None value
self.PDF_path = None
except Exception as es:
messagebox.showerror('Error!', f"Error due to {es}")

Perform the Decrypt Operation

The logic for decryption is the same as the Encryption operation.


# Function to perform Decryption Operation
def Decrypt_PDF(self):
if self.ent_password.get() == '':
messagebox.showwarning('Warning', "Please set the password")
else:
try:
# Read the PDF file
pdfFile = PdfFileReader(self.PDF_path)
pdfWriter = PdfFileWriter()
# The Result file: Same name as the original
result = open(self.PDF_path, 'wb')

# Decrypt the PDf file
pdfFile.decrypt(password=self.ent_password.get())

# Iterate through every pages of the PDF file
for page in range(pdfFile.getNumPages()):
# Add the page to the pdfWriter variable
pdfWriter.addPage(pdfFile.getPage(page))

# Write the Result file
pdfWriter.write(result)

messagebox.showinfo('Done!',"The PDf file has been unlocked")
# Calling the Home_Page() function
self.Home_Page()
# Set the self.PDF_path None value
self.PDF_path = None
except Exception as es:
messagebox.showerror('Error!', f"Error due to {es}")

The main function

Now declare the main function. Here, we will create a Tk() class object, and an 'En_Dec_rypt' class object. The Tkinter event loop(mainloop) will start running from here.


# The main function
if __name__ == "__main__":
root = Tk()
# Creating a 'En_Dec_rypt' class object
obj = En_Dec_rypt(root)
root.mainloop()

Convert the PDF locker and Unlocker program to an Executable file

Here, I will show how to make a python program into an executable file for Windows and Linux both.

convert python program to exe file - PySeek

Do install PyInstaller at first. Use pip instead of pip3 for Windows.

pip3 install pyinstaller

Windows

Go to the command prompt and change the current working directory to the folder where the python file is. Then run this command.

pyinstaller --onefile -w Secure_PDF.py

Linux

Almost the same logic for Linux except for a small change in the command.

pyinstaller --onefile Secure_PDF.py

Summary

In this tutorial, we've done a very useful python project using the Tkinter library. We built an Application using Python to Encrypt and Decrypt PDF files by Password. We used two python libraries in this project: Tkinter(to manage the graphical interface), and PyPDF2(for working with PDF files).

For the users' convenience, we learn to convert this application program to an executable file at the end. 

I hope you loved this tutorial. You're also welcome to give me any further suggestions to improve this Application. You can share your opinion in the comment section.

To get more lovely Tkinter Examples, visit the separate page created only for Python Projects. Some examples are given below.

👉A GUI YouTube Video Downloader using Python Tkinter

👉Image to Pencil Sketch Converter in Python

👉Countdown Timer in Python - with Start and Pause Function

If you encounter any problems while running this project, let me know. You will receive an immediate response. 

Thanks for reading!💙 

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post