python - 加密的 PDF 不会写入磁盘

标签 python python-3.x pypdf

我有一些加密 pdf 的代码,由于某种原因,一旦我加密 pdf,书写就会挂起。如果我注释掉 pdf_writer.encrypt(password) 就没有问题,并且内容写入正确。我尝试以最高权限运行脚本并修改文件夹选项,但也许我错过了一些简单的东西。

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)

任何帮助将不胜感激。

最佳答案

我不明白为什么 PyPDF2 不起作用,所以我只是尝试了另一个名为 pikepdf 的模块,一切正常。无论如何,这实际上看起来是一个比 PyPDF2 更好的模块。

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))

关于python - 加密的 PDF 不会写入磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56760409/

相关文章:

python - `conda uninstall` 和 `pip uninstall` 是否也删除了依赖项但仅删除了其他包未使用的依赖项?

Python:使用 YAML 自动创建类方法

python - 在 PuLP 中实现特定约束

c++ - Python 将输入重定向到子进程

python - 在嵌入式 Python 解释器中跟踪代码执行

python - python中从PDF中提取图像时出错

python - 如何提取pdf文档的语言

python - 解决 "EOF market not found error"PyPDF2

python - 为什么通过ip访问可以,但是域访问失败?

python - 如何将 Pytorch 张量拆分为不同的维度?