如何使用PDFMiner获取PDF中文本的位置? [英] How does one obtain the location of text in a PDF with PDFMiner?

查看:953
本文介绍了如何使用PDFMiner获取PDF中文本的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PDFMiner的文档说:

PDFMiner's documentation says:

PDFMiner允许人们获取页面中文本的确切位置

PDFMiner allows one to obtain the exact location of text in a page

但是,我无法找到如何执行此操作. PDFMiner的文档"相当少,所以我不知道该怎么做.

However, I have not been able to find how to do this. PDFMiner's 'documentation' is rather sparse, so I have not understood how to do this.

推荐答案

您正在寻找每个布局对象上的bbox属性. PDFMiner文档中有关于如何解析布局层次结构的一些信息,但没有覆盖一切.

You are looking for the bbox property on every layout object. There is a little bit of information on how to parse the layout hierarchy in the PDFMiner documentation, but it doesn't cover everything.

这是一个例子:

from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFigure


def parse_layout(layout):
    """Function to recursively parse the layout tree."""
    for lt_obj in layout:
        print(lt_obj.__class__.__name__)
        print(lt_obj.bbox)
        if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
            print(lt_obj.get_text())
        elif isinstance(lt_obj, LTFigure):
            parse_layout(lt_obj)  # Recursive


fp = open('example.pdf', 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)

rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.create_pages(doc):
    interpreter.process_page(page)
    layout = device.get_result()
    parse_layout(layout)

如果您对单个LTChar对象的位置感兴趣,则可以递归地解析为LTTextBoxLTTextLine的子布局对象,就像上面示例中对LTFigure所做的一样.

If you are interested in the location of individual LTChar objects, you can recursively parse into the child layout objects of LTTextBox and LTTextLine just like what is done with LTFigure in the above example.

这篇关于如何使用PDFMiner获取PDF中文本的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆