Here I am going to show you an example how to encrypt PDF to make it password protected using PyPDF2 module in Python programming language. Piece of cake 🍰
This example we are going to read the existing PDF file and making this PDF file password protected.
It is a pretty simple idea to make the PDF password protected when you want to send some sensitive data into the PDF file over the network, such as, email or you are allowing end users to download the PDF files.
✱ Prerequisites:
- Python 3.9.1
- PyPDF2 1.26.0
Installation:
pip install pypdf2
The code:
import PyPDF2
pdfFile = open('example.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt('password')
resultPdf = open('encrypted_output.pdf', 'wb')
pdfWriter.write(resultPdf)
resultPdf.close()
Pop-up:
Password Remove:
Installation:
pip install pikepdf
The code:
import pikepdf
pdf_loc = input("PDF location: ")
pdf_pass = input("PDF password: ")
pdf = pikepdf.open(pdf_loc, password=pdf_pass)
print("\nProcessing...\n")
pdf_save = input("Save file as: ")
pdf_loc2 = input("Save location: ")
pdf.save(pdf_loc2 + '\\' + pdf_save)
print("The password successfully removed from the PDF")
print("\aLocation: " + pdf_loc + '\\' + pdf_save)
Terminal:
Congratulations, right now, you can open PDF files without being bothered with the password.
Comments