I'm trying to automate some processes at work. I am able to merge PDFs from a list and able to take that merged PDF to create an encrypted PDF. Right now, I am stuck trying to take an existing encrypted PDF, decrypt it, and merge it with the other members of a list. Every time I decrypt and try to merge with a unencrypted PDF, My error message reads "File has not been decrypted." Below is my code up until where I need to merge encrypted and unencrypted PDFS.
Does PyPDF2 only allow you to READ encrypted PDFs using the decrypt method? Should I create a new list for encrypted PDFs and append to that? Is it possible to decrypt a PDF, copy its contents, and create a new unencrypted file? Any help would be much appreciated. Thank you.
import os
import PyPDF2
os.chdir(r'C:\Users\######\Downloads')
#Here I merge Two dummy PDFs
pdfs = ['Gateway Parking Form.pdf', 'sample.pdf']
merger = PyPDF2.PdfFileMerger()
for pdf in pdfs:
merger.append(pdf)
merger.write("result.pdf")
merger.close
#Here I copy the contents of the merged file to create a new encrypted PDF
pdfFile = open("result.pdf", "rb")
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt("HelloDude")
resultPdf = open("result_Client.pdf", "wb")
pdfWriter.write(resultPdf)
pdfFile.close()
resultPdf.close()
#Here I WANT to decrypt the password-protected PDF and merge it with two dummy PDFs
pdfs = ['Gateway Parking Form.pdf', 'sample.pdf', "result_Client.pdf"]
for pdf in pdfs:
pdfFile = open(pdf, "rb")
reader = PyPDF2.PdfFileReader(pdfFile)
writer = PyPDF2.PdfFileWriter()
if reader.isEncrypted:
reader.decrypt("HelloDude")
def decryption(input_name,output_name,password):
pdfFile = open(input_name, "rb")
reader = PyPDF2.PdfFileReader(pdfFile)
writer = PyPDF2.PdfFileWriter()
if reader.isEncrypted:
reader.decrypt(password)
for pageNum in range(reader.numPages):
writer.addPage(reader.getPage(pageNum))
resultPdf = open(output_name, "wb")
writer.write(resultPdf)
pdfFile.close()
resultPdf.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.