2024-09-30 Web Development
How to Unlock Multiple PDF Files in a Folder Using Python
By O Wolfson
Unlocking multiple PDF files individually can be a tedious task, especially if you have a large number of them. Fortunately, Python provides an efficient way to automate this process. Let's create a Python script that unlocks all PDF files in a specified folder and saves the unlocked versions with a modified filename.
Step 1: Set Up a Virtual Environment
To ensure a clean and isolated environment for our project, we will use a virtual environment. This is especially useful on a Mac to avoid conflicts with system-wide packages.
-
Open Terminal and navigate to your project directory:
-
Create a virtual environment named
pdf-unlocker-env
: -
Activate the virtual environment:
Step 2: Install Required Package
We will use the pikepdf
library to unlock the PDFs. With the virtual environment activated, install pikepdf
:
Step 3: Create the Python Script
Create a Python script named unlock_pdfs_in_folder.py
in your project directory:
Open unlock_pdfs_in_folder.py
with your preferred text editor and add the following code:
Step 4: Run the Script
To unlock all PDF files in a folder, run the script with the folder path and the password as arguments:
Explanation of the Script
- Unlock a Single PDF: The
unlock_pdf
function takes the input PDF path, output PDF path, and password to unlock a single PDF file using thepikepdf
library. - Process Multiple PDFs: The
unlock_pdfs_in_folder
function iterates over all files in the specified folder, checking if they have a.pdf
extension. If so, it constructs the input and output paths and callsunlock_pdf
. - Command-Line Arguments: The script accepts two command-line arguments: the folder path containing the PDFs and the password to unlock them.
Deactivate the Virtual Environment
After you're done, you can deactivate the virtual environment by running: