Python PyPDF2 – Encrypt a PDF file

In this post we will be creating a Python script that will encrypt a PDF file, to do this we will be using the PyPDF2 library. The PyPDF2 is a Python library that enables users to perform various operations on PDF documents. It provides a range of functions for reading, editing, and manipulating PDF files, such as merging and splitting PDFs, extracting text and images, and encrypting and decrypting content.

See the sample of Python code below where we utilize the PyPDF2 module to encrypt a PDF file, we start by initiating our PDF reader to read from our existing PDF. We then move on to writing its content to a new encrypted PDF and save this as a new file.

If using the code below you would replace the ‘YourPassword’ with a password of your own choice.

from PyPDF2 import PdfReader, PdfWriter

pdf_reader = PdfReader("file.pdf")
pdf_writer = PdfWriter()

pdf_writer.encrypt(user_password='YourPassword', use_128bit=True)

for page in pdf_reader.pages:
    pdf_writer.add_page(page)

with open("encrypted_file.pdf", "wb") as out:
    pdf_writer.write(out)

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply