Skip to content

Instantly share code, notes, and snippets.

@vinodnimbalkar
Created August 12, 2020 04:11
Show Gist options
  • Save vinodnimbalkar/e7b2f4a53084bb7cb20d53ab5b5dc763 to your computer and use it in GitHub Desktop.
Save vinodnimbalkar/e7b2f4a53084bb7cb20d53ab5b5dc763 to your computer and use it in GitHub Desktop.
bulk password protected pdf
import PyPDF2
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
pdfdirectory = input("Pease provide pdf directory name : ")
user_pass = input("Pease provide password to protect pdf file : ")
PDFDIR = os.listdir(f"{BASEDIR}/{pdfdirectory}/")
def set_password():
"""
Function creates new temporary pdf file with same content,
assigns given password to pdf and rename it with original file.
"""
# temporary output file with name same as input file but prepended
# by "temp_", inside same direcory as input file.
try:
for input_file in PDFDIR:
print(f"Protecting : {input_file}")
path, filename = os.path.split(input_file)
output_file = os.path.join(path, "temp_" + filename)
output = PyPDF2.PdfFileWriter()
input_path = f"{BASEDIR}/{pdfdirectory}/{input_file}"
output_path = f"{BASEDIR}/{pdfdirectory}/{output_file}"
input_stream = PyPDF2.PdfFileReader(open(input_path, "rb"))
for i in range(0, input_stream.getNumPages()):
output.addPage(input_stream.getPage(i))
outputStream = open(output_path, "wb")
# Set user and owner password to pdf file
output.encrypt(user_pass, None, use_128bit=True)
output.write(outputStream)
outputStream.close()
# Rename temporary output file with original filename, this
# will automatically delete temporary file
os.rename(output_path, input_path)
except Exception as err:
print(err)
if __name__ == "__main__":
set_password()
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment