Password for PDF via Python

Ashish Bansal
1 min readSep 23, 2020

Easy code to password protect PDF files using PyPDF2 Python library.

Lock those files: Photo by Waldemar Brandt

No more premium apps are required, just use the simple python script to lock the PDF files, just follow the simple 5 step approach.

  1. Provide the file path/name as per <Open_Doc.pdf>.
  2. Give output file name as per <Pass_Protected_PDF_Name.pdf.
  3. Select password as per<PA$$WO%D>.
  4. Run this Python script via your IDE or CLI.
  5. Now the our file should be generated with specified password.
import PyPDF2 as password #import as function
out = password.PdfFileWriter() #for performing actions on files
originalfile = password.PdfFileReader(open("<Open_Doc.pdf>", "rb"))

for i in range(0, originalfile.getNumPages()): #Iterate for number of total pages.
out.addPage(originalfile.getPage(i))

newfile = open("<Pass_Protected_PDF_Name.pdf>", "wb") #Output file

out.encrypt("<PA$$WO%D>", use_128bit=True) #Provide Password
out.write(newfile)
newfile.close() #Close open file

I don’t think much of a explanation is required for the above code but you can always message me or refer to the project documentation as per Click here

~AshishSecDev

--

--