【问题标题】:How to process PDFs in-memory using python?如何使用python处理内存中的PDF?
【发布时间】:2019-02-22 05:28:43
【问题描述】:

背景:

我有一个包含多页的 PDF 文件 (LARGE_PDF)。每个页面都包含一个表格,没有其他内容。每张桌子看起来都不一样。我想提取表格内容并将它们放入熊猫数据框中。我为此使用tabula-py,它可以通过以下方法按需要工作:

方法:

首先,我将 PDF 文件拆分为多个单页 PDF 文件并保存到光盘。

single_page_files = split_and_save(LARGE_PDF) # Split to single files, one page each

其次,将每个文件提供给 tabula-py。

from tabula import read_pdf as tabular_read 

for item in single_page_files:                
    print type(item)
    df = tabular_read(PDF_page, pandas_options={'header':None})
    if df:
         print 'approach works'

输出:

>>> <type 'str'>                              # filepath string
>>> approach works

挑战:

我现在想在内存中执行此操作,以便不会将中间单页 pdf 文件保存到磁盘。为此,我创建了一个单页 PyPDF2.pdf.PageObject 对象列表并将它们提供给 tabula-py。

from PyPDF2 import PdfFileReader, PdfFileWriter

single_page_pypdfobjects = split_but_dont_save(LARGE_PDF)
for item in single_page_pypdfobjects:                
    print type(item)
    df = tabular_read(PDF_page, pandas_options={'header':None})
    if df:
         print 'approach works'

输出:

>>> class 'PyPDF2.pdf.PageObject'>             # PyPDF2 single page object
>>> TypeError: unhashable type

如何使用 python 处理内存中的 PDF?

【问题讨论】:

标签: python pdf in-memory pypdf2


【解决方案1】:

您不需要拆分 PDF。 Tabla-py 有一个选项 pages 告诉它您要从哪些页面中提取。

【讨论】:

  • 感谢您的评论。我知道那个选项。由于各种原因,我需要拆分。我无法改变这种方法。
  • 那么您必须使用临时文件,因为 Tabla 不支持将其他任何内容作为输入。好吧,它确实支持类似文件的对象,但在内部它通过将它们写入文件来处理它们。
  • 我很惊讶。我在文档中没有找到任何关于此的内容。 StringIO 对象或类似的东西呢?
  • read_pdf 调用localize_file,后者通过获取类文件对象和 URL 并将其复制到文件中来处理它们。
猜你喜欢
  • 1970-01-01
  • 2011-05-27
  • 2013-01-22
  • 2012-04-04
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多