Encrypt and Decrypt PDF using PyPDF2

Encrypt and Decrypt PDF using PyPDF2

Using PyPDF2, you can encrypt and decrypt PDF files in Python. Below are steps and code snippets for both tasks:

1. Encrypting a PDF

To encrypt a PDF file, you can use the encrypt() method on a PdfFileWriter object.

import PyPDF2 def encrypt_pdf(input_pdf, output_pdf, password): # Creating a pdf file reader object pdf_reader = PyPDF2.PdfFileReader(input_pdf) # Creating a pdf writer object pdf_writer = PyPDF2.PdfFileWriter() # Adding all pages to the writer object for page_num in range(pdf_reader.numPages): page = pdf_reader.getPage(page_num) pdf_writer.addPage(page) # Encrypting the pdf pdf_writer.encrypt(password) # Writing encrypted pages to the new file with open(output_pdf, "wb") as output_file_handle: pdf_writer.write(output_file_handle) # Usage encrypt_pdf("path_to_input_pdf", "path_to_encrypted_pdf", "your_password") 

2. Decrypting a PDF

To decrypt a PDF file, you can use the decrypt() method on a PdfFileReader object.

import PyPDF2 def decrypt_pdf(input_pdf, output_pdf, password): # Creating a pdf file reader object pdf_reader = PyPDF2.PdfFileReader(input_pdf) # Check if the PDF is encrypted if pdf_reader.isEncrypted: # If it's encrypted, try to decrypt using the provided password success = pdf_reader.decrypt(password) if not success: raise ValueError("Incorrect password provided for decryption") # Creating a pdf writer object for the output file pdf_writer = PyPDF2.PdfFileWriter() # Adding all pages to the writer object for page_num in range(pdf_reader.numPages): page = pdf_reader.getPage(page_num) pdf_writer.addPage(page) # Writing decrypted pages to the new file with open(output_pdf, "wb") as output_file_handle: pdf_writer.write(output_file_handle) # Usage decrypt_pdf("path_to_encrypted_pdf", "path_to_decrypted_pdf", "your_password") 

Note:

  • Always keep backups of your original PDFs. Encryption and decryption processes, especially with third-party libraries, might occasionally lead to data corruption or loss.
  • PyPDF2 has limitations and may not work with all PDFs, especially more complex ones. If you encounter issues, consider using alternative libraries or tools.

More Tags

sql-server-2000 maven-ear-plugin data-science java.nio.file react-router shader delta-lake directory uisearchbardelegate derived-column

More Programming Guides

Other Guides

More Programming Examples