【问题标题】:Reading a pdf from a zipfilePyPDF2:从 zip 文件中读取 pdf
【发布时间】:2020-09-15 05:54:39
【问题描述】:

我正在尝试让 PyPDF2 读取一个简单的 zip 文件中的小型 .pdf 文件。到目前为止,这是我所得到的:

import PyPDF2,zipfile

with zipfile.ZipFile("TEST.zip") as z:
    filename = z.namelist()[0]
    a = z.filelist[0]
    b = z.open(filename)
    c = z.read(filename)
    PyPDF2.PdfFileReader(b)

错误信息:

PdfReadWarning: PdfFileReader stream/file object is not in binary mode. It may not be read correctly. [pdf.py:1079]
io.UnsupportedOperation: seek

感谢任何想法!谢谢。

【问题讨论】:

    标签: python zipfile pypdf2


    【解决方案1】:

    该文件尚未解压,因此您无法使用open() 对其进行操作。

    不过没关系,因为PdfFileReader 想要一个流;所以我们可以使用BytesIO 提供它。下面的示例获取解压缩的字节,并将它们提供给 BytesIO,后者将它们变成 PdfFileReader 的流。如果你省略了 BytesIO,你会得到:AttributeError: 'bytes' object has no attribute 'seek'

    import PyPDF2,zipfile
    from io import BytesIO                             
    
    with zipfile.ZipFile('sample.zip','r') as z: 
        filename = z.namelist()[0] 
        pdf_file = PyPDF2.PdfFileReader(BytesIO(z.read(filename))) 
    

    结果:

    In [20]: pdf_file
    Out[20]: <PyPDF2.pdf.PdfFileReader at 0x7f01b61db2b0>
    
    In [21]: pdf_file.getPage(0)
    Out[21]: 
    {'/Type': '/Page',
     '/Parent': {'/Type': '/Pages',
      '/Count': 2,
      '/Kids': [IndirectObject(4, 0), IndirectObject(6, 0)]},
     '/Resources': {'/Font': {'/F1': {'/Type': '/Font',
        '/Subtype': '/Type1',
        '/Name': '/F1',
        '/BaseFont': '/Helvetica',
        '/Encoding': '/WinAnsiEncoding'}},
      '/ProcSet': ['/PDF', '/Text']},
     '/MediaBox': [0, 0, 612, 792],
     '/Contents': {}}
    

    【讨论】:

    • @AkibRhast:谢谢。你的答案是正确的!
    • 嗯,我也认为它是,但在我发布我的之后。看了你的,测试了你的,它奏效了。回头看看我的,意识到我没有使用 OP 显然想要的 PyPDF2。意识到我的答案在应用 PyPDF2 时会中断。因为正如你提到的,它需要一个流。因此,如果我没记错的话,您使用 BytesIo 的答案是将输出转换为流并提供给 PyPDF2,对吗?
    • 是的,完全正确。我将在解释中更清楚地说明。谢谢!
    • 这绝对是完美的——非常感谢!这个io.bytesio我听说过,但是没用过。
    • 当然!任何时候你有一个字符串并且你正在使用的东西都需要一个文件。它基本上是一个类似于上面的类似文件的字符串,这里的 BytesIO 是一个类似文件的字节流。因此,例如,如果您想将字符串写入 zip 文件,您可以使用 StringIO 发送到 zipfile,而不必写入文件然后压缩它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2019-03-16
    • 2020-12-16
    • 1970-01-01
    • 2012-03-09
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多