Encrypt Your Pdf Using Python

How To Encrypt PDF As Password Protected File In Python

Encrypt Your Pdf Using  Python

Portable Document Format (PDF ) is one of the most used file formats for storing and sending documents. They are commonly used for many purposes such as eBooks, Resumes, Scanned documents, etc. But as we share pdf with many people, there is a possibility of its data getting leaked or stolen. So, it’s necessary to password protect our PDF files so that only authorized persons can have access to it.

In this article, we are going to see how can we set a password to protect a PDF file. I’ll be using the PyPDF2 module to encrypt  our PDF files. 

Whats PyPDF2

PyPDF2 is a Python library built as a PDF toolkit. It is capable of:

  • Extracting document information (title, author, …)
  • Splitting and Merging documents
  • Cropping pages
  • Encrypting and decrypting PDF files

Installation:

pip3 install PyPDF2

Code:

from PyPDF2 import PdfFileWriter,PdfFileReader
out=PdfFileWriter()
file_path="sample.pdf"
file=PdfFileReader(file_path)
num=file.numPages
for idx in range(num):
    page=file.getPage(idx)
    out.addPage(page)
password="hello"
out.encrypt(password)
with open("encrypted_file.pdf","wb")asf:
    out.write(f)

Code Explanation:

1. The code starts by importing the PdfFileWriter and PdfFileReader classes.
2. It then creates a file path, which is "sample.pdf", and creates an instance of the PdfFileReader class with that file path.
3. Next, it gets the number of pages in the PDF document using numPages from the reader object's getPage method.
4. Then it iterates through each page in turn to create a new page for itself on every iteration.
5. Finally, it encrypts its password using addPage before writing out all of its pages to a new PDF file called encrypted_file.pdf
6. The code encrypts the contents of a PDF file with a password and saves it to another PDF file.