Add Password to PDF in Python [Download Complete Solution]

As a Python developer, I often work with PDF files that contain confidential information. Many times, I needed to share PDFs securely with clients or team members, but I wanted to restrict unauthorized access.

Instead of using online tools, I decided to build my own Add Password to PDF Tool using Python and Streamlit.

This tool allows users to upload a PDF file, create a strong password, and instantly download a password-protected version of the PDF.

You can also download the complete Python project and try it out.

Add Password to PDF in Python

I developed an Add Password to PDF Tool using Python and the Streamlit library. Streamlit helps build the user interface, while PyPDF handles PDF encryption and password protection. The tool allows users to upload PDF files, enter a password, validate password strength, and download the protected PDF.

Installation:

pip install streamlit pypdf

Libraries Used in the Python Add Password to PDF Tool

import streamlit as st
from pypdf import PdfReader, PdfWriter
from io import BytesIO
import random
import string
import re

streamlit

Streamlit is used to design and manage the complete user interface of the application. It handles file uploads, password fields, buttons, success messages, error messages, and downloads.

pypdf

PyPDF is responsible for reading PDF files, copying pages, and encrypting the PDF using a user-provided password. It acts as the core engine behind the password-protection functionality.

BytesIO

BytesIO allows the protected PDF to be created directly in memory without storing temporary files on the system.

random

The random module is used to generate secure random passwords when users click the password generator button.

string

The string module provides uppercase letters, lowercase letters, digits, and special characters required for generating strong passwords.

re

The re module is used for password validation, such as checking uppercase letters, lowercase letters, numbers, and special characters.

User Controls in Python: Add Password to PDF Tool

You will get a Browse Files button, using which you can upload a PDF file. After uploading the PDF, you will see two password fields: Enter Password and Confirm Password. You can either enter a password manually or click the Generate Password button to automatically create a strong password.

Once a valid password is provided and all validations are satisfied, you can click the Protect PDF button to encrypt the PDF file. After the encryption process is completed successfully, a Download Protected PDF button will appear, allowing you to download the password-protected PDF file instantly.

Python’s Streamlit has a default server upload limit of 200 MB. Changing this limit must be done outside your application code.

Locate your project folder

Create a folder named:

.streamlit

Inside the .streamlit folder, create a file named:

config.toml

Add the following code inside the config.toml file:

[server]
maxUploadSize = 10
Add Password to PDF Python

The above configuration sets the maximum PDF upload size to 10 MB. You can modify this value according to your requirements.

Validations Used in Python: Add Password to PDF Tool

To ensure security and smooth operation, multiple validations are implemented.

  • PDF File Type Validation: Only PDF files are accepted. Any other file format is rejected.
elif uploaded_pdf.type != "application/pdf":
            st.error("Only PDF files are allowed.")
  • Maximum File Size Validation: The application accepts PDF files up to 10 MB. Files larger than the configured limit are rejected.
elif uploaded_pdf.size > MAX_FILE_SIZE:
            st.error("File size should be less than 10 MB.")
  • Empty Password Validation: The password field cannot be empty.
Python Add Password to PDF
  • Empty Confirm Password Validation: Users must confirm their password.
  • Password Match Validation: The password and confirm password fields must contain identical values.
elif password != confirm_password:
            st.error("Passwords do not match.")
  • Minimum Password Length Validation: Passwords must contain at least 6 characters.
elif len(password) < 6:
            st.error("Password must be at least 6 characters.")
  • Maximum Password Length Validation: Passwords cannot exceed 20 characters.
if len(password) > 20:
                    st.error("Password should not exceed 20 characters.")
                    st.stop()
  • Already Protected PDF Validation: If the uploaded PDF is already encrypted, processing stops, and a warning is displayed.
Add Password to PDF in Python Using Streamlit
  • PDF Contains No Pages Validation: The application checks whether the uploaded PDF contains at least one page. Empty PDFs are rejected.
  • Password Same as File Name Validation: Passwords should not be identical to the PDF file name.
if password.lower() == filename.lower():
                    st.error("Password should not be same as file name.")
                    st.stop()
  • Common Password Validation: Common passwords such as:
123456
password
admin
qwerty

are blocked because they are easy to guess.

  • Uppercase Letter Validation: Passwords must contain at least one uppercase letter.

Example:

elif not re.search(r"[A-Z]", password):
            st.error("Password must contain at least one uppercase letter.")
Python PDF Password Protection Tool Interface
  • Number Validation: Passwords must contain at least one numeric value.

Example:

elif not re.search(r"[0-9]", password):
            st.error("Password must contain at least one number.")
  • Special Character Validation: Passwords must contain at least one special character.

Example:

elif not re.search(r"[!@#$%^&*()_+=<>?/]", password):
            st.error("Password must contain at least one special character.")

Password Generator Feature

The application includes a built-in password generator which contains: Uppercase letters, Lowercase letters, Numbers, and Special characters. This ensures that generated passwords automatically satisfy all password requirements.

Add Password to PDF Tool Output

Upload PDF and Add Password Using Python

Download Encrypted PDF

Protect PDF Files with Password in Python

Conclusion

In this tutorial, I developed an Add Password to PDF Tool using Python, Streamlit, and PyPDF. The application allows users to upload PDF files, apply password protection, generate strong passwords, validate user input, and download encrypted PDFs securely. The tool provides a simple and secure way to protect confidential PDF documents before sharing them with others.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.