I need help creating a code that takes PDF files in a specified folder, and adds a password for editing. Then saves the password protected PDF files into a specified folder. The goal is to make the PDFs locked for editing, but essentially turning them to 'Read Only'. I've played around a bit, but so far I've only been able to lock the PDF completely, which defeats the purpose of what I need.
import os
import PyPDF2
def encrypt_pdf(input_path, output_path, password):
# iterate over all pdf files in the input folder
for file_name in os.listdir(input_path):
if file_name.endswith('.pdf'):
file_path = os.path.join(input_path, file_name)
# read the pdf file
with open(file_path, 'rb') as pdf_file:
pdf_reader = PyPDF2.PdfReader(pdf_file)
pdf_writer = PyPDF2.PdfWriter()
# add all pages to the writer object
for page_num in range(len(pdf_reader.pages)):
pdf_writer.add_page(pdf_reader.pages[page_num])
# set encryption options
pdf_writer.encrypt(user_pwd=password, owner_pwd=password, permissions_flag=0b0100)
# write the encrypted pdf to the output folder
output_file_path = os.path.join(output_path, file_name)
with open(output_file_path, 'wb') as output_file:
pdf_writer.write(output_file)
# set input and output folder paths
input_folder = r'C:\Users\dargenal\Documents\0A - Test Folder (doc to pdf)\PDF Backup'
output_folder = r'C:\Users\dargenal\Documents\0A - Test Folder (doc to pdf)\PDF Backup\Secured (Locked) PDF'
# set encryption password
password = 'mypassword'
# encrypt pdf files in input folder and write them to output folder
encrypt_pdf(input_folder, output_folder, password)