Password for PDF via Python
1 min readSep 23, 2020
Easy code to password protect PDF files using PyPDF2 Python library.
No more premium apps are required, just use the simple python script to lock the PDF files, just follow the simple 5 step approach.
- Provide the file path/name as per <Open_Doc.pdf>.
- Give output file name as per <Pass_Protected_PDF_Name.pdf.
- Select password as per<PA$$WO%D>.
- Run this Python script via your IDE or CLI.
- 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