Member-only story

PDF file protection using password in Python

Python Coding
2 min readNov 12, 2024

--

from PyPDF2 import PdfReader, PdfWriter
import getpass

def protect_pdf(input_pdf, output_pdf):
reader = PdfReader('clcoding.pdf')
writer = PdfWriter()

for page in reader.pages:
writer.add_page(page)

password = getpass.getpass("Enter a password : ")
writer.encrypt(password)
with open(output_pdf, "wb") as output_file:
writer.write(output_file)
print(f"The PDF has password.")

protect_pdf("clcoding.pdf", "protected_file.pdf")

This code uses the PyPDF2 library to add password protection to a PDF file. Here's a breakdown:

Imports:

  • PdfReader and PdfWriter are imported from PyPDF2, a library for working with PDF files in Python.
  • getpass is imported to securely prompt the user to enter a password without displaying it on the screen.

Function Definition:

  • protect_pdf(input_pdf, output_pdf) is a function that takes two parameters:
  • input_pdf: the name of the PDF file to protect.
  • output_pdf: the name of the newly created protected PDF file.

Reading and Copying Pages:

  • reader = PdfReader('clcoding.pdf'): A PdfReader instance is created to read the contents of input_pdf (in this case, 'clcoding.pdf').

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet