The Wayback Machine - https://web.archive.org/web/20240704164237/https://www.geeksforgeeks.org/encrypt-and-decrypt-pdf-using-pypdf2/
Open In App

Encrypt and Decrypt PDF using PyPDF2

Last Updated : 01 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

PDF (Portable Document Format) 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 to 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. We’ll be using the PyPDF2 module to encrypt and decrypt our PDF files. 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

PyPDF2 is not an inbuilt library, so we have to install it.

pip3 install PyPDF2

Now, we are ready to write our script to encrypt PDF files.

Encrypting the PDF File

First, We will open our PDF file with the reader object. Then, we will create a copy of the original file so that if something goes wrong, it doesn’t affect our original file. To create a copy, we have to iterate through every page of the file and add it to our new PDF file. Then, we can simply encrypt our new PDF file.

PDF File used:

Python3




# import PdfFileWriter and PdfFileReader 
# class from PyPDF2 library
from PyPDF2 import PdfFileWriter, PdfFileReader
  
# create a PdfFileWriter object
out = PdfFileWriter()
  
# Open our PDF file with the PdfFileReader
file = PdfFileReader("myfile.pdf")
  
# Get number of pages in original file
num = file.numPages
  
# Iterate through every page of the original 
# file and add it to our new file.
for idx in range(num):
    
    # Get the page at index idx
    page = file.getPage(idx)
      
    # Add it to the output file
    out.addPage(page)
  
  
# Create a variable password and store 
# our password in it.
password = "pass"
  
# Encrypt the new file with the entered password
out.encrypt(password)
  
# Open a new file "myfile_encrypted.pdf"
with open("myfile_encrypted.pdf", "wb") as f:
    
    # Write our encrypted PDF to this file
    out.write(f)


Output:

This will create a copy of the original file and encrypt it with the entered password. Once the PDF is encrypted, it can not be opened without entering the correct password.

Decrypting The PDF File

But what if we want to decrypt the encrypted PDF file? We can do this too with this library. The process is almost the same. We will open the encrypted file with the correct password and create a copy of it by iterating through every page of it and adding it to our new PDF file.

Here’s the code:

Python3




# import PdfFileWriter and PdfFileReader 
# class from PyPDF2 library
from PyPDF2 import PdfFileWriter, PdfFileReader
  
# Create a PdfFileWriter object
out = PdfFileWriter()
  
# Open encrypted PDF file with the PdfFileReader
file = PdfFileReader("myfile_encrypted.pdf")
  
# Store correct password in a variable password.
password = "pass"
  
# Check if the opened file is actually Encrypted
if file.isEncrypted:
  
    # If encrypted, decrypt it with the password
    file.decrypt(password)
  
    # Now, the file has been unlocked.
    # Iterate through every page of the file
    # and add it to our new file.
    for idx in range(file.numPages):
        
        # Get the page at index idx
        page = file.getPage(idx)
          
        # Add it to the output file
        out.addPage(page)
      
    # Open a new file "myfile_decrypted.pdf"
    with open("myfile_decrypted.pdf", "wb") as f:
        
        # Write our decrypted PDF to this file
        out.write(f)
  
    # Print success message when Done
    print("File decrypted Successfully.")
else:
    
    # If file is not encrypted, print the 
    # message
    print("File already decrypted.")


This will create a copy of the encrypted file that doesn’t require a password to be opened.

So, this was a basic script to encrypt and decrypt PDF files. But there are a plethora of ideas to extend this. You can create a GUI tool to do it or Develop a Web application that encrypts PDF files. You can also create a whole PDF Manager using the PyPDF2 library.



Similar Reads

Encrypt and Decrypt Image using Python
In this article, we will encrypt/decrypt an image using simple mathematical logic. It requires two things, data, and key, and when XOR operation is applied on both the operands i.e data and key, the data gets encrypted but when the same process is done again with the same key-value data gets decrypted. Encryption It is nothing but a simple process
5 min read
Encrypt and Decrypt Files using Python
Encryption is the act of encoding a message so that only the intended users can see it. We encrypt data because we don't want anyone to see or access it. We will use the cryptography library to encrypt a file. The cryptography library uses a symmetric algorithm to encrypt the file. In the symmetric algorithm, we use the same key to encrypt and decr
3 min read
How to Encrypt and Decrypt Strings in Python?
In this article, we will learn about Encryption, Decryption and implement them with Python. Encryption: Encryption is the process of encoding the data. i.e converting plain text into ciphertext. This conversion is done with a key called an encryption key. Decryption: Decryption is the process of decoding the encoded data. Converting the ciphertext
4 min read
How to Install "Python-PyPDF2" package on Linux?
PyPDF2 is a Python module for extracting document-specific information, merging PDF files, separating PDF pages, adding watermarks to files, encrypting and decrypting PDF files, and so on. PyPDF2 is a pure python module so it can run on any platform without any platform-related dependencies on any external libraries or packages. So, in this article
2 min read
Send PDF File through Email using pdf-mail module
pdf_mail module is that library of Python which helps you to send pdf documents through your Gmail account. Installing Library This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install pdf-mail Function of pdf_mail This module only comes with a singl
2 min read
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values & Binary forms for all printable characters, which allows us to operate bit-wise logic like XOR and most encryption/decryption algorithms depend on. The Key is XOR-operated on the plain text to produce the encrypted text. Only Parameters required to encrypt a plain text using this technique: P
2 min read
Encrypt the String according to the given algorithm in Python
Given a string s, the task is to encrypt the string in the following way. Let the string be "apple". Step 1: Reverse the input: "elppa" Step 2: Replace all vowels using the following chart: a => 0 e => 1 i => 2 o => 2 u => 3 Resultant string - "1lpp0" Step 3: Add "aca" to the end of the word: Resultant String: "1lpp0aca" Examples: In
2 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Build an Application to extract URL and Metadata from a PDF using Python
The PDF (Portable Document Format) is the most common use platform-independent file format developed by Adobe to present documents. There are lots of PDF-related packages for Python, one of them is the pdfx module. The pdfx module is used to extract URL, MetaData, and Plain text from a given PDF or PDF URL. Features: Extract references and metadata
3 min read
Take and convert Screenshot to PDF using Python
In order to take and convert a screenshot to PDF, firstly the PyAutoGUI can be used which is an automation library in python which can control mouse, keyboard and can handle many GUI control tasks. Secondly, for the conversion PIL(Python Imaging Library) of python can be used which provides image processing facility and it supports many file format
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg