Skip to content

Instantly share code, notes, and snippets.

@elip-OE
Forked from bzamecnik/decrypt_pdf.py
Last active January 7, 2021 13:40
Show Gist options
  • Save elip-OE/0dbbbed8c5f6b062d86223038a70bea1 to your computer and use it in GitHub Desktop.
Save elip-OE/0dbbbed8c5f6b062d86223038a70bea1 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 argparse import ArgumentParser
from PyPDF2 import PdfFileReader, PdfFileWriter
def decrypt_pdf(input_path, output_file, password):
with open(input_path, "rb") as input_file, open(output_file, '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)
def getopt():
parser = ArgumentParser()
parser.add_argument("-i", "--input", dest="file_path", help="file path to decrypt")
parser.add_argument("-p", "--password", dest="password", help="password of file")
parser.add_argument("-o", "--output", dest="out_path", help="path to write decrypted file")
return parser.parse_args()
def main(options):
decrypt_pdf(options.file_path, options.out_path, options.password)
if __name__ == "__main__":
main(getopt())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment