Member-only story
PDF file protection using password in Python
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
andPdfWriter
are imported fromPyPDF2
, 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')
: APdfReader
instance is created to read the contents ofinput_pdf
(in this case,'clcoding.pdf'
).