Skip to content

dorian-sotpyrc/build-a-python-pdf-encryptor

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build a Python PDF Encryptor in 20 Lines

A tiny, well-commented Python script that encrypts a PDF with a password in about 20 lines of code.

Overview

This repo shows how to build a self-contained PDF encryptor in Python that can lock any PDF file with a password. The focus is on clarity and minimalism: a single script, a single function, and just enough code to be understandable for beginners.

By the end, you’ll be able to run one command (or a short Python snippet) to take an existing PDF and produce a password-protected version.

This repository supports the PLEX tutorial:

Build a Python PDF Encryptor in 20 Lines
https://plexdata.online/post/build-a-python-pdf-encryptor-in-20-lines

You can also follow Dorian’s broader writing on Medium:
https://medium.com/@doriansotpyrc


Features

  • 🔐 Password-protect any PDF using a single function.
  • 🧾 Minimal code (~20 lines), easy to read and adapt.
  • 🧩 No complex frameworks – just Python and pypdf.
  • 🧪 Includes a small test to verify that encryption runs successfully.
  • 🧑‍💻 Works both as a CLI script and as an importable function.

Project Structure

build-a-python-pdf-encryptor/
├── pdf_encryptor.py        # ~20-line core script to encrypt a PDF with a password
├── examples/
│   └── demo_encrypt.py     # Example usage importing the encrypt function
├── tests/
│   └── test_pdf_encryptor.py  # Minimal test to verify encrypted output is created
├── requirements.txt        # External dependency pin (pypdf)
└── README.md               # Project documentation and usage guide

How It Works

At a high level:

  1. Read the input PDF using pypdf.PdfReader.
  2. Copy all pages into a new pypdf.PdfWriter object.
  3. Apply encryption with a user-supplied password.
  4. Write the encrypted PDF to a new file.

Conceptual flow:

[input.pdf] --read--> [PdfReader] --copy pages--> [PdfWriter] --encrypt(password)--> [encrypted.pdf]

The core logic lives in a single function encrypt_pdf inside pdf_encryptor.py. The same file also exposes a small CLI so you can run it directly from the command line.


Installation

  1. Clone the repo
git clone git@github-dorian:dorian-sotpyrc/build-a-python-pdf-encryptor.git
cd build-a-python-pdf-encryptor
  1. (Optional) Create and activate a virtual environment
python -m venv .venv
# Windows
.venv\\Scripts\\activate
# macOS / Linux
source .venv/bin/activate
  1. Install dependencies
pip install -r requirements.txt

This will install pypdf, the only external dependency.


Usage

1. Command-line usage

You can run the encryptor directly as a script:

python pdf_encryptor.py input.pdf output_encrypted.pdf mypassword
  • input.pdf – path to the existing PDF you want to protect.
  • output_encrypted.pdf – path where the encrypted PDF will be written.
  • mypassword – the password required to open the encrypted PDF.

Example:

python pdf_encryptor.py examples/sample.pdf examples/sample_encrypted.pdf secret123

If the command finishes without errors, you should see sample_encrypted.pdf in the examples/ directory. Open it with a PDF viewer and you’ll be prompted for the password secret123.

2. Import and use from Python

You can also import the function in your own scripts:

from pdf_encryptor import encrypt_pdf

encrypt_pdf(
    input_path="examples/sample.pdf",
    output_path="examples/sample_encrypted.pdf",
    password="secret123",
)

A complete example is provided in examples/demo_encrypt.py.

Run it with:

python examples/demo_encrypt.py

Code Walkthrough (20-line core)

The heart of the project is the encrypt_pdf function in pdf_encryptor.py. It:

  1. Opens the input PDF with PdfReader.
  2. Creates a PdfWriter and copies each page.
  3. Calls writer.encrypt(password).
  4. Writes the result to output_path.

The script also includes a small if __name__ == "__main__": block that parses three command-line arguments and calls encrypt_pdf.

The code is heavily commented so you can understand each step even if you’re new to Python or PDF libraries.


Running Tests

This repo includes a minimal test to verify that encryption runs and produces an output file.

  1. Install pytest (if you don’t already have it):
pip install pytest
  1. Run tests from the repo root:
pytest

The test in tests/test_pdf_encryptor.py will:

  • Create a tiny one-page PDF in memory.
  • Save it to a temporary file.
  • Call encrypt_pdf to produce an encrypted version.
  • Assert that the encrypted file exists and is readable.

PLEX Article & Further Reading

This repo is explained in more detail in the PLEX article:
https://plexdata.online/post/build-a-python-pdf-encryptor-in-20-lines

You can also follow Dorian’s broader writing on Medium:
https://medium.com/@doriansotpyrc

There you’ll find more tutorials on Python, security, and practical automation.


Roadmap / Extensions

If you want to extend this project, here are some ideas:

  • Batch encryption: encrypt all PDFs in a folder with the same password.
  • Password prompt: hide the password input using getpass instead of passing it on the command line.
  • GUI wrapper: build a tiny Tkinter or PyQt interface for non-technical users.
  • Decryption helper: add a companion function to decrypt PDFs (where you know the password).
  • Metadata handling: preserve or modify PDF metadata (title, author, etc.) during encryption.

License

This project is licensed under the MIT License. You are free to use, modify, and distribute it, with attribution.

About

Learn how to create a simple PDF encryptor using Python in just 20 lines of code.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages