Whether you are handling confidential client agreements, employee pay slips, financial statements, or academic records, password-protecting sensitive documents is non-negotiable. However, if you have ever tried to protect more than a handful of documents at once, you have likely run into a frustrating bottleneck: how do you password protect multiple PDF files simultaneously without wasting hours opening them one by one?
Most commercial software vendors lock batch PDF security behind steep paywalls. Adobe Acrobat Pro charges a hefty recurring subscription ($19.99 per month, or nearly $240 every year) just to access its Batch Action Wizard. Meanwhile, free online file converters usually limit uploads to two or three files at a time—and worse, uploading confidential bank statements, employee records, or legal contracts to unknown third-party cloud servers poses a massive data privacy risk.
In this guide, you will learn how to automate this entire workflow locally using a lightweight, open-source Python batch encryption script. By running this simple script on your computer, you can encrypt 10, 50, or 500 PDF files in seconds with enterprise-grade AES encryption—completely free, 100% offline, and without sending a single byte of private data across the internet.
| Method | Batch Speed | Cost | Data Privacy |
|---|---|---|---|
| Adobe Acrobat Pro | Moderate (Action Wizard) | $239.88 / year | Local desktop |
| Online PDF Converters | Slow (2–3 files max) | Free / Freemium | High Risk (Cloud Upload) |
| Manual One-by-One | Extremely Slow | Free | Local desktop |
| Python Batch Script | Lightning Fast (Bulk) | 100% Free Forever | 100% Offline & Private |
Why Automate PDF Encryption with Python?
Automating PDF protection through Python offers distinct advantages over manual desktop tools and online web apps:
- Zero Cost Forever: The Python PDF ecosystem is open source. You never have to pay license fees or worry about expired trials.
- Absolute Privacy & Compliance: The script executes 100% locally on your machine. Your sensitive records never leave your hard drive, ensuring strict compliance with GDPR, HIPAA, and corporate confidentiality policies.
- High-Speed Batch Processing: Encrypting 100 PDFs manually in Acrobat takes 20 to 30 minutes. A Python batch loop executes the same task in less than 5 seconds.
- Customizable Passwords: You can apply a uniform master password to an entire folder, or dynamically pull unique employee passwords directly from a CSV spreadsheet.
Prerequisites & Environment Setup
To run the batch encryption script, you only need Python installed on your system along with the modern pypdf library (the official, actively maintained successor to the legacy PyPDF2 package).
Step 1: Check Python Installation
Open your terminal (PowerShell or Command Prompt on Windows, Terminal on macOS/Linux) and verify that Python is available:
python --version
If you don’t have Python installed, download the latest stable release from the official python.org website. Make sure to check the box that says “Add Python to PATH” during installation.
Step 2: Install the pypdf Library
Install the pypdf package via pip by running the following command in your terminal:
pip install pypdf
Note: If you have an older script using PyPDF2, pypdf is the drop-in replacement that includes improved performance, 256-bit AES encryption support, and bug fixes for modern PDF syntax.
Step 3: Setting Up Your Folder Structure
To keep your files organized and avoid accidentally overwriting your original documents, organize a clean project folder on your computer:
PDF_Security_Project/
│
├── batch_encrypt.py # Your Python automation script
├── input_pdfs/ # Place your unencrypted PDF files here
└── encrypted_pdfs/ # Output folder for password-protected PDFs
- Create a new directory named
PDF_Security_Project. - Inside it, create a subfolder called
input_pdfsand drop all the PDF documents you wish to protect inside. - The script will automatically create the
encrypted_pdfsfolder when it executes.
Step 4: The Core Python Batch Encryption Script
Create a file named batch_encrypt.py inside your project directory and paste the following production-ready Python script:
import os
from pypdf import PdfReader, PdfWriter
def batch_encrypt_pdfs(input_dir, output_dir, password):
"""
Scans input_dir for all PDF files, encrypts each document with
the specified password, and saves the protected file to output_dir.
"""
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# Retrieve all PDF files from the input directory
pdf_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.pdf')]
if not pdf_files:
print(f"[!] No PDF files found in '{input_dir}'. Please add some documents.")
return
print(f"[+] Found {len(pdf_files)} PDF file(s) to encrypt...")
success_count = 0
for idx, filename in enumerate(pdf_files, start=1):
input_path = os.path.join(input_dir, filename)
output_filename = f"protected_{filename}"
output_path = os.path.join(output_dir, output_filename)
try:
reader = PdfReader(input_path)
# Check if the PDF is already password protected
if reader.is_encrypted:
print(f"[-] Skipped '{filename}': File is already encrypted.")
continue
writer = PdfWriter()
# Transfer all pages from reader to writer
for page in reader.pages:
writer.add_page(page)
# Encrypt the document with 128-bit or 256-bit AES
writer.encrypt(user_password=password, algorithm="AES-256")
# Save the protected PDF
with open(output_path, "wb") as output_file:
writer.write(output_file)
print(f"[{idx}/{len(pdf_files)}] Successfully protected: {output_filename}")
success_count += 1
except Exception as e:
print(f"[!] Error processing '{filename}': {str(e)}")
print("\n" + "="*50)
print(f"[✓] Batch Encryption Complete: {success_count}/{len(pdf_files)} files protected successfully!")
print(f"[✓] Protected files saved to: {os.path.abspath(output_dir)}")
if __name__ == "__main__":
# Define directories
INPUT_FOLDER = "input_pdfs"
OUTPUT_FOLDER = "encrypted_pdfs"
# Set your secure password
# Tip: Use our free tool at umairalam.com/password-generator to create strong passwords!
MASTER_PASSWORD = "SecurePass@2026#Global"
batch_encrypt_pdfs(INPUT_FOLDER, OUTPUT_FOLDER, MASTER_PASSWORD)
Step 5: Executing the Script & Verifying Results
Once you have configured your folder paths and password, execute the script from your terminal:
python batch_encrypt.py
Expected Console Output:
[+] Found 5 PDF file(s) to encrypt...
[1/5] Successfully protected: protected_Annual_Financial_Report.pdf
[2/5] Successfully protected: protected_Client_NDA_Contract.pdf
[3/5] Successfully protected: protected_Employee_Payroll_Q3.pdf
[4/5] Successfully protected: protected_Tax_Assessment_Form.pdf
[5/5] Successfully protected: protected_Audit_Summary_2026.pdf
==================================================
[✓] Batch Encryption Complete: 5/5 files protected successfully!
[✓] Protected files saved to: C:\Users\Umair\PDF_Security_Project\encrypted_pdfs
When you navigate into the encrypted_pdfs directory and attempt to open any generated document in Adobe Acrobat, Microsoft Edge, or Chrome, you will immediately be greeted with a password prompt requiring the master key before any content or page thumbnail is displayed.
Advanced Techniques: User vs. Owner Passwords & Permissions
In standard PDF security architecture, there are two distinct types of passwords:
- User Password (Open Password): Required to unlock, view, and read the document. Without this password, the PDF cannot be opened.
- Owner Password (Permissions Password): Allows document owners to restrict specific actions—such as prohibiting document printing, preventing text copying, or disallowing annotations—even if a user can open and view the file.
With pypdf, you can specify both passwords and define exact security permissions in your batch script:
writer.encrypt(
user_password="ClientViewOnly2026",
owner_password="AdminMasterSecret99#",
permissions_flag={
"print": False, # Disallow printing
"modify": False, # Disallow edits and alterations
"copy": False, # Disallow copying text and graphics
"annotate": False # Disallow adding comments or forms
},
algorithm="AES-256"
)
This allows organizations to send viewable files to clients or contractors while preventing them from copying sensitive proprietary code, text, or figures.
Generating Cryptographically Strong Passwords
A protected PDF is only as secure as the password guarding it. Short dictionary words (like admin123 or company2024) can be cracked by basic brute-force scripts in under 60 seconds.
For maximum security, ensure your passwords follow these standards:
- Length: Minimum of 14 to 16 characters.
- Entropy: A blend of uppercase letters, lowercase letters, numbers, and symbols.
- Unique Credentials: Avoid reusing master passwords across different client file batches.
- Free Generator: Use my on-site Free Online Password Generator to instantly generate cryptographically strong, high-entropy passwords with custom length and special character sets.
Free Online Tool Alternative (No Code Required)
If you only have one or two documents and don’t want to run a Python terminal script, you can use browser-based tools without installing any software:
- Before locking your document, if you need to apply official company seals, approval marks, or watermarks across all pages, visit my Free Online PDF Stamper.
- To combine scattered contracts or invoices into a single master document before encryption, use my Free PDF Merger.
- Explore my complete suite of browser-based document utilities in the Free Online PDF Tools Hub.
Frequently Asked Questions (FAQ)
1. Can someone remove the password from the encrypted PDF?
If the PDF is encrypted using modern AES-128 or AES-256 encryption, it is mathematically impossible to decrypt or strip the password without either the User password or Owner password. Standard brute-force attacks against strong 16-character passwords would take centuries.
2. Does this script overwrite or delete my original PDF files?
No. The script reads files from the input_pdfs folder and outputs freshly encrypted copies prefixed with protected_ into the separate encrypted_pdfs folder. Your original unencrypted documents remain untouched.
3. Can I assign a different, unique password to each individual file?
Yes! By pairing the Python script with a CSV or Excel file containing file names and corresponding passwords (e.g. employee_id, password), you can loop through the dictionary and protect each document with an individualized key. This is the exact pattern used for automated monthly payroll slips.
4. Will this script work on Mac, Windows, and Linux?
Yes. Python and the pypdf library are 100% platform-independent. The exact same script runs seamlessly across Windows 11/10, macOS Sonoma/Sequoia, and Ubuntu/Debian Linux distributions.
Related Tutorials & System Security Guides
- How to Add Stamp and Watermark to PDF Files Online for Free
- Excel Data Security: Lock Cells, Protect Sheets & Workbook Structure
- 12 Useful Windows Commands Every Power User Should Know
- How to Share a Google Sheet Securely: Viewer vs. Commenter vs. Editor
- Automate Web Forms to Google Sheets & Gmail with n8n