Remove password from your pdf payslips

by GarciaPL on Thursday 22 February 2018

Within my previous employers, I was getting those payslips protected with a password. One day I thought what is going to happen if I would forget or lose the password! That's why I decided to write a small script in Python which might automate removing password from your payslip (or any other file).


# Requirements:
# pip install PyPDF2

import os
from PyPDF2 import PdfFileReader, PdfFileWriter

password = 'password'
directory = '/path/where/pdfs/are/stored'

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__':
  newDirectory = directory + "/Decoded"
  if not os.path.exists(newDirectory):
    os.makedirs(newDirectory)
  for filename in os.listdir(directory):
    if filename.endswith(".pdf"): 
      fullFileName = os.path.join(directory, filename)
      decrypt_pdf(fullFileName, newDirectory + "/" + filename, password)

Reference :
[1] Pastebin