Skip to content

Instantly share code, notes, and snippets.

@bzamecnik
Created January 18, 2017 07:54
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save bzamecnik/1abb64affb21322256f1c4ebbb59a364 to your computer and use it in GitHub Desktop.
Save bzamecnik/1abb64affb21322256f1c4ebbb59a364 to your computer and use it in GitHub Desktop.
Decrypt password-protected PDF in Python.
# 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')
@jvishwa06
Copy link

How to Use This Code

@Drezzler
Copy link

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)

@jvishwa06
Copy link

Thank You Bro , You're Awesome !

@SanthoshRNaidu90433
Copy link

Great Sir, Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment