2025-12-11

Build a Python PDF Encryptor in 20 Lines

Python, Security, Automation · Dorian Sotpyrc

Why a lightweight PDF encryptor is worth having

PDFs remain the de-facto format for sharing reports, statements, and sensitive documents. But most PDFs are sent exactly as they are—unencrypted, forwardable, and readable by humans and automation alike. A tiny Python encryptor gives you a fast way to add a layer of protection before you send anything outward.

Python PDF encryptor script example
A minimal Python encryptor that locks any PDF behind a password.
Before we get into it

Just want a working implementation? Download the completed GitHub repo: python-qr-generator-tool on GitHub.

Just want a QR code without writing Python? Use the online tool: PLEX PDF Password — paste a URL or text and download a PNG instantly.

Step 1 — Install the only dependency

This encryptor uses PyPDF2, a lightweight library for reading and writing PDF files.

BASH
pip install PyPDF2

Step 2 — Create a 20-line PDF encryptor

Save the following script as encrypt.py. It reads a PDF, copies every page to a writer object, applies a password, and saves the encrypted file.

PYTHON

#!/usr/bin/env python3
"""
Minimal PDF encryptor using PyPDF2.
"""

import PyPDF2

def encrypt_pdf(input_pdf: str, output_pdf: str, password: str) -> None:
    with open(input_pdf, "rb") as file:
        reader = PyPDF2.PdfReader(file)
        writer = PyPDF2.PdfWriter()

        for page in reader.pages:
            writer.add_page(page)

        writer.encrypt(password)

        with open(output_pdf, "wb") as out:
            writer.write(out)

if __name__ == "__main__":
    encrypt_pdf("input.pdf", "encrypted.pdf", "your_password")
    print("Encrypted PDF saved to encrypted.pdf")
    

How the script works

The function encrypt_pdf does everything:

  1. Load the original PDF
    PdfReader extracts pages without modifying the source file.
  2. Copy every page into a writer
    PdfWriter builds a new PDF in memory, giving us full control over output settings.
  3. Apply a password
    writer.encrypt(password) locks the new PDF and requires the password on open.
  4. Write the encrypted output
    The encrypted PDF is saved wherever you specify—ready to share.
Download the full project

The complete source, including variations and tests, is available on GitHub:
https://github.com/dorian-sotpyrc/build-a-python-pdf-encryptor

Next steps: strengthen your workflow

This minimal encryptor is a great utility to keep nearby. You can extend it with:

  • Batch encryption for folders containing many PDFs
  • A GUI wrapper using Tkinter or PySide
  • Integration into automated reporting pipelines
  • Metadata scrubbing before encryption

For organisations needing stronger access controls, tamper-resistant consent steps, and AI-aware protection, see the PLEX AILock solution.

Related PLEX reading

References & further reading