使用PYTHON使用PYPDF2加密许多PDF



我正在尝试制作一个python程序,该程序通过文件夹中的所有文件循环,选择具有扩展名的'.pdf'的程序,然后使用受限的权限加密它们。我正在使用此版本的PYPDF2库:https://github.com/vchatterji/pypdf2。(对原始PYPDF2的修改也允许设置权限)。我已经用一个PDF文件对其进行了测试,并且可以正常工作。我希望原始的PDF文件应删除,并且加密文件应保留为相同的名称。这是我的代码:

import os
import PyPDF2
directory = './'
for filename in os.listdir(directory):
    if filename.endswith(".pdf"): 
        pdfFile = open(filename, 'rb')
        pdfReader = PyPDF2.PdfFileReader(pdfFile)
        pdfWriter = PyPDF2.PdfFileWriter()
        for pageNum in range(pdfReader.numPages):
            pdfWriter.addPage(pdfReader.getPage(pageNum))
        pdfFile.close()
        os.remove(filename)
        pdfWriter.encrypt('', 'ispat', perm_mask=-3904)
        resultPdf = open(filename, 'wb')
        pdfWriter.write(resultPdf)
        resultPdf.close()
        continue
    else:
        continue

它给出以下错误:

  C:UsersmanulDesktopghh>python encrypter.py
  Traceback (most recent call last):
  File "encrypter.py", line 9, in <module>
  pdfReader = PyPDF2.PdfFileReader(pdfFile)
  File "C:UsersmanulAppDataLocalProgramsPythonPython37libsite-packagesPyPDF2pdf.py", line 1153, in __init__
  self.read(stream)
  File "C:UsersmanulAppDataLocalProgramsPythonPython37libsite-packagesPyPDF2pdf.py", line 1758, in read
    stream.seek(-1, 2)
  OSError: [Errno 22] Invalid argument

我在桌面上的" GHH"文件夹中存储了一些PDF。任何帮助都非常感谢。

使用 pdfReader = PyPDF2.PdfFileReader(filename)将使读取器起作用,但是此特定错误是由您的文件空的。您可以使用os.path.getsize(filename)检查文件尺寸。您的文件可能被擦除了,因为脚本删除了原始文件,然后使用open(filepath, "wb")创建一个新文件,然后由于pdfWriter.write(resultPdf)发生的错误而终止错误,将一个带有原始文件名称的空文件留下。

将文件名而不是文件对象传递到PdfFileReader,如上所述,可以解决pdfWriter发生的错误(我不知道为什么),但是您需要用原始的副本替换目录中的任何空文件pdfs摆脱了Oserror。

最新更新