I am trying to password protect a pdf file using python.I have come across a solution using PyPDF2 library but the solution does not work on the version of 3.0.0 or above.
Below is the code
# import PdfFileWriter and PdfFileReader # class from PyPDF2 libraryfrom PyPDF2 import PdfFileWriter, PdfFileReader# create a PdfFileWriter objectout = PdfFileWriter()# Open our PDF file with the PdfFileReaderfile = PdfFileReader("myfile.pdf")# Get number of pages in original filenum = file.numPages# Iterate through every page of the original # file and add it to our new file.for idx in range(num): # Get the page at index idx page = file.getPage(idx) # Add it to the output file out.addPage(page)# Create a variable password and store # our password in it.password = "pass"# Encrypt the new file with the entered passwordout.encrypt(password)# Open a new file "myfile_encrypted.pdf"with open("myfile_encrypted.pdf", "wb") as f: # Write our encrypted PDF to this file out.Write(f)
If anyone can help me with the solution, that will be helpful.
Thank you