繁体   English   中英

使用PyPDF2通过python加密许多PDF

[英]Encrypting many PDFs by python using PyPDF2

我正在尝试制作一个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:\Users\manul\Desktop\ghh>python encrypter.py
  Traceback (most recent call last):
  File "encrypter.py", line 9, in <module>
  pdfReader = PyPDF2.PdfFileReader(pdfFile)
  File "C:\Users\manul\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\pdf.py", line 1153, in __init__
  self.read(stream)
  File "C:\Users\manul\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\pdf.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发生的错误(我不知道为什么),但是您需要将目录中的任何空文件替换为原始pdf的副本才能获取摆脱OSError。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM