Creating Password-Protected PDFs with Python ReportLab


Interactive Google Colab Practice Notebook

Practice building single password-protected PDFs, batch unique password-encrypted documents from list data, and setting user vs owner permissions directly inside Google Colab.

View on GitHub Open In Colab

We'll start with a simple example of creating a single password-protected PDF and then move on to generating multiple PDFs with unique passwords for each file.

Creating a Single Password-Protected PDF 🔝

Creating a Secure PDF with Python ReportLab: Step-by-Step Guide Part-1
from pathlib import Path
from reportlab.pdfgen import canvas
from reportlab.lib import pdfencrypt

output_dir = Path('output')
output_dir.mkdir(exist_ok=True)
my_path = output_dir / 'single_protected.pdf'

pw = pdfencrypt.StandardEncryption('test')
c = canvas.Canvas(str(my_path), bottomup=0, encrypt=pw)
c.drawString(50, 200, "Hello World")
c.showPage()
c.save()
print(f"Single protected PDF created: {my_path}")

Let's break down the code step by step:

  1. Import the necessary modules:
    from reportlab.pdfgen import canvas
    from reportlab.lib import pdfencrypt
  2. Define the password for the PDF:
    pw = pdfencrypt.StandardEncryption('test')
  3. Specify the file path where the PDF will be saved using pathlib.Path:
    my_path = Path('output/single_protected.pdf')
  4. Create the canvas object with specified path and encryption:
    c = canvas.Canvas(str(my_path), bottomup=0, encrypt=pw)
  5. Draw text on the PDF canvas:
    c.drawString(50, 200, "Hello World")
  6. Save the page and finalize canvas:
    c.showPage()
    c.save()

Creating Multiple Password-Protected PDFs 🔝

Creating Multiple Password-Protected PDFs from data sets using Python ReportLab Part II

from pathlib import Path
from datetime import datetime
from reportlab.pdfgen import canvas
from reportlab.lib import pdfencrypt

output_dir = Path('output')
output_dir.mkdir(exist_ok=True)

l1 = [
    (1, 'John Deo', 'Four', 75, 'female', '2010-02-25'),
    (2, 'Max Ruin', 'Three', 85, 'male', '2010-12-12'),
    (3, 'Arnold', 'Three', 55, 'male', '2011-03-31')
]

for rows in l1:
    f = rows[0]
    my_path = output_dir / f'my_pdf_{f}.pdf'
    
    dt = datetime.strptime(rows[5], '%Y-%m-%d')
    str_dt = datetime.strftime(dt, '%b')
    str_name = rows[1][0:3]
    str_pw = (str_name + str_dt).lower()
    
    pw = pdfencrypt.StandardEncryption(str_pw)
    c = canvas.Canvas(str(my_path), bottomup=0, encrypt=pw)
    my_data = f"{rows[0]},{rows[1]},{rows[2]},{rows[3]},{rows[4]}"
    c.drawString(50, 200, my_data)
    c.showPage()
    c.save()
    print(f"Generated {my_path} with password '{str_pw}'")

Generated Files & Passwords Overview

Filename Generated Password
my_pdf_1.pdf johfeb
my_pdf_2.pdf maxdec
my_pdf_3.pdf arnmar

The Logic Behind Unique Password Creation

The unique password for each PDF file is generated by combining the first three characters of the name and the abbreviated month part of the date, both converted to lowercase.

For example, the name "John Deo" and date "2010-02-25" produce the password "johfeb".

Restricting Editing and Printing Permissions in PDFs 🔝

How to set User and Master level password for different activities in PDF file in Reportlab Part-III

With the PDF security handler, we can specify two types of passwords for a document:

  • Owner Password: Also referred to as the 'master password' or 'security password'. Provides unrestricted access to modify permissions.
  • User Password: Also referred to as the 'open password'. Opens the document with restricted capabilities.
from pathlib import Path
from reportlab.pdfgen import canvas
from reportlab.lib import pdfencrypt

output_dir = Path('output')
output_dir.mkdir(exist_ok=True)
my_path = output_dir / 'restricted_permissions.pdf'

pw = pdfencrypt.StandardEncryption(
    userPassword='xyz',
    ownerPassword='abc',
    canPrint=False,
    canModify=False,
    canCopy=False,
    canAnnotate=False
)

c = canvas.Canvas(str(my_path), bottomup=0, encrypt=pw)
c.drawString(50, 200, "This PDF is password and permission protected")
c.showPage()
c.save()
print(f"Restricted permission PDF generated: {my_path}")

Practical Uses of PDF Encryption 🔝

  • Automated Payslip & Invoice Delivery: Protect confidential financial records by encrypting PDFs with recipient-specific passwords (e.g. employee ID + birth month).
  • Intellectual Property Protection: Restrict text copying (`canCopy=False`) and editing (`canModify=False`) on draft eBooks, contracts, and research reports.
  • Controlled Distribution: Prevent unauthorized printing (`canPrint=False`) for sensitive institutional or legal documents.

Common Errors & Troubleshooting 🔝

  • Invalid Type Error on Path Passing: ReportLab canvas expects a string path. When using `pathlib.Path`, always cast to string: `canvas.Canvas(str(my_path))`.
  • Encryption Object Reuse: Instantiating `pdfencrypt.StandardEncryption` outside a batch generation loop reuses the same state. Always instantiate a new `StandardEncryption` object inside each iteration loop for unique passwords.
  • Case-Sensitivity Issues: Password strings like `"JohFeb"` vs `"johfeb"` will fail if capitalization isn't normalized. Use `.lower()` or `.upper()` consistently.

Frequently Asked Questions (FAQ) 🔝

Q: Can I encrypt existing PDF files without recreating them?
A: ReportLab creates PDFs from scratch. To encrypt existing PDF files, use libraries like pypdf or PyMuPDF.

Q: What is the difference between User and Owner passwords?
A: The User password allows viewing under restricted permissions. The Owner password unlocks all restrictions and enables permission changes.

Questions & Self-Assessment 🔝


PDF Table from different data sources to PDF file
Bar charts in PDF Line charts in PDF Pie Charts Paragraph
Python



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer