Skip to content

Instantly share code, notes, and snippets.

@rainly
Forked from linyiru/decrypt_pdf.py
Created October 10, 2018 14:27
Show Gist options
  • Save rainly/cc8b9eb9e14c92ddb45a2592f5504b02 to your computer and use it in GitHub Desktop.
Save rainly/cc8b9eb9e14c92ddb45a2592f5504b02 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')
import sys
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__':
# Use shell script to pass the filename, e.g.: python3 convert.py "$1"
decrypt_pdf(sys.argv[1], sys.argv[1] + "_decrypted.pdf", 'YOUR_PASSWORD')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment