-
-
Save bzamecnik/1abb64affb21322256f1c4ebbb59a364 to your computer and use it in GitHub Desktop.
# Decrypt password-protected PDF in Python. | |
# cleaned-up version of http://stackoverflow.com/a/26537710/329263 | |
# | |
# Requirements: | |
# pip install PyPDF2 | |
# | |
# Usage: decrypt_pdf('encrypted.pdf', 'decrypted.pdf', 'secret_password') | |
from PyPDF2 import PdfFileReader, PdfFileWriter | |
def decrypt_pdf(input_path, output_path, password): | |
with open(input_path, 'rb') as input_file, \ | |
open(output_path, 'wb') as output_file: | |
reader = PdfFileReader(input_file) | |
reader.decrypt(password) | |
writer = PdfFileWriter() | |
for i in range(reader.getNumPages()): | |
writer.addPage(reader.getPage(i)) | |
writer.write(output_file) | |
if __name__ == '__main__': | |
# example usage: | |
decrypt_pdf('encrypted.pdf', 'decrypted.pdf', 'secret_password') |
Below is the updated version with support for PyPDF2 > 3.0
from PyPDF2 import PdfReader, PdfWriter
def decrypt_pdf(input_path, output_path, password):
with open(input_path, 'rb') as input_file, \
open(output_path, 'wb') as output_file:
reader = PdfReader(input_file)
reader.decrypt(password)
writer = PdfWriter()
for i in range(len(reader.pages)):
writer.add_page(reader.pages[i])
writer.write(output_file)
Thank You Bro , You're Awesome !
Great Sir, Thank you
I have some important PDF files containing standards and regulations. These files are encrypted with a plugin for a PDF viewer like Acrobat or Foxit. The plugin (FIL30P3N) allowed me to temporarily view the PDFs. Unfortunately, that permission has expired. Now I can't access these valuable PDFs.
Is it possible to recover them using Python?
@nairoleon For decryption you need the password. With it you can open the PDF in any PDF reader.
This script serves a different purpose. It makes a copies the contents of the an encrypted PDF (using the password for decryption) into a new PDF which does not use any encryption.
Thanks @bzamecnik . My pdf files do not ask for a password to open them, only this error appears in any pdf viewer when I try to open.
How to Use This Code