A tiny, well-commented Python script that encrypts a PDF with a password in about 20 lines of code.
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
- 🔐 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.
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
At a high level:
- Read the input PDF using
pypdf.PdfReader. - Copy all pages into a new
pypdf.PdfWriterobject. - Apply encryption with a user-supplied password.
- 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.
- Clone the repo
git clone git@github-dorian:dorian-sotpyrc/build-a-python-pdf-encryptor.git
cd build-a-python-pdf-encryptor- (Optional) Create and activate a virtual environment
python -m venv .venv
# Windows
.venv\\Scripts\\activate
# macOS / Linux
source .venv/bin/activate- Install dependencies
pip install -r requirements.txtThis will install pypdf, the only external dependency.
You can run the encryptor directly as a script:
python pdf_encryptor.py input.pdf output_encrypted.pdf mypasswordinput.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 secret123If 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.
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.pyThe heart of the project is the encrypt_pdf function in pdf_encryptor.py. It:
- Opens the input PDF with
PdfReader. - Creates a
PdfWriterand copies each page. - Calls
writer.encrypt(password). - 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.
This repo includes a minimal test to verify that encryption runs and produces an output file.
- Install
pytest(if you don’t already have it):
pip install pytest- Run tests from the repo root:
pytestThe test in tests/test_pdf_encryptor.py will:
- Create a tiny one-page PDF in memory.
- Save it to a temporary file.
- Call
encrypt_pdfto produce an encrypted version. - Assert that the encrypted file exists and is readable.
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.
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
getpassinstead 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.
This project is licensed under the MIT License. You are free to use, modify, and distribute it, with attribution.