Search code examples
pythonpython-3.xpypdf

Encrypted PDF won't write to disk


I have some code that is encrypting a pdf, and for some reason as soon as I encrypt the pdf, the writing hangs. If I comment out pdf_writer.encrypt(password) there is no problem and things are written properly. I've tried running the script with the highest privileges and modifying the folder options, but maybe I'm missing something simple.

with open(filename, 'rb') as pdf_file:
    pdf_reader = PyPDF2.PdfFileReader(pdf_file)
    pdf_writer = PyPDF2.PdfFileWriter()

    for page_number in range(pdf_reader.numPages):
        pdf_writer.addPage(pdf_reader.getPage(page_number))

    pdf_writer.encrypt(password)
    filename_encrypted = filename.parents[0] / f "{filename.stem}_encrypted.pdf"

    with open(filename_encrypted, 'wb') as pdf_file_encrypted:
        pdf_writer.write(pdf_file_encrypted)

Any help would be greatly appreciated.


Solution

  • I couldn't figure out why things weren't working with PyPDF2, so I just tried another module called pikepdf and things worked just fine. This actually seems like a much better module than PyPDF2 anyway.

    import pikepdf
    
    
    filename = pathlib.Path(r"path\to\pdf\test.pdf")
    password = 'password'
    
    with Pdf.open(filename) as pdf:
        filename_encrypted = filename.parents[0] / f"{filename.stem}_encrypted.pdf"
        pdf.save(filename_encrypted, encryption=Encryption(user=password, owner=password))