Add/Remove PDF Password Using Python

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


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):
resultPdf = open('encrypted_output.pdf', 'wb')


Password Remove:


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)


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)


Congratulations, right now, you can open PDF files without being bothered with the password.


21 views0 comments

Recent Posts

See All

Run Python Automation Script to fetch Cisco Routers and Switches details in Bulk. The details includes ā€œhostname, uptime, current version, current image, serial number, device model, device memoryā€ Pr

Most of us have seen the dreaded ā€œNo Internetā€ error message on Google Chrome. You can actually turn this screen into a fun, dino-themed endless runner game and, even better, hack the hidden Easter eg

In this post you will learn how you can save pictures from Instagram account in your PC using Python. You just need to install "instalooter" into your Python packages and run the command. There are ma