DEV Community

Cover image for .py : Adding Password Protection
Bhushan Rane
Bhushan Rane

Posted on

1

.py : Adding Password Protection

Description:

This Python script adds password protection to a PDF file. It encrypts the PDF with a password, ensuring that only those with the correct password can access the content.

# Python script to add password protection to a PDF
import PyPDF2
def add_password_protection(input_path, output_path, password):
with open(input_path, 'rb') as f:
pdf_reader = PyPDF2.PdfFileReader(f)
pdf_writer = PyPDF2.PdfFileWriter()
for page_num in range(pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
pdf_writer.addPage(page)
pdf_writer.encrypt(password)
with open(output_path, 'wb') as output_file:
pdf_writer.write(output_file)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sreno77 profile image
Scott Reno

This is useful... thanks!

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay