Hi Pythonistas!
While working with python another important thing protecting pdf will be a password. Some of the critical PDF files are encrypted using a password. Today we will learn how to encrypt and decrypt PDF files. Let us dive into the code
Encrypting File
from PyPDF2 import PdfReader, PdfWriter
reader = PdfReader("sample.pdf")
writer = PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.encrypt("password")
with open("encrypted-pdf.pdf", "wb") as f:
writer.write(f)
writer.encrypt("password") This will encrypt the file with password “password”. If you try to open the file a password prompt will be shown. If you specify the password then only the content of this file is shown.
Decrypting file
from PyPDF2 import PdfReader, PdfWriter
reader = PdfReader("encrypted-pdf.pdf")
writer = PdfWriter()
if reader.is_encrypted:
reader.decrypt("password")
for page in reader.pages:
writer.add_page(page)
with open("decrypted-pdf.pdf", "wb") as f:
writer.write(f)
reader.is_encrypted - check whether the file is encrypted, If file encrypted then a True is returned
reader.decrypt("password") - Decrypt the file using the proper password, If wrong password error is given it will raise an PyPDF2.errors.FileNotDecryptedError exception.
I hope you have learned something from this post. Please share your valuable suggestion with afsal@parseltongue.co.in