top of page

Add/Remove PDF Password Using Python

Writer: Diniz MartinsDiniz Martins

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.



Recent Posts

See All

Fake Data in Python

If you are developing applications, testing your software, or just exploring Python's capabilities, you might have faced a situation...

Mobile | Secret Phone Codes

Our smartphones have become extensions of ourselves, facilitating much of our communication and storing troves of private data. If...

Mouse & Keyboard Bot

This article illustrates how to automate mouse and keyboard movements using pyautogui module in python. This module is not preloaded with...

Comments


Programming and IT solutions guide on STENGE.info blog
Cybersecurity and Networking tutorials on STENGE.info
IT infrastructure solutions and technology tutorials
STENGE.info logo - Tech Blog for IT Solutions and Tutorials
bottom of page