How does one obtain the location of text in a PDF with PDFMiner? How does one obtain the location of text in a PDF with PDFMiner? python python

How does one obtain the location of text in a PDF with 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.

Here's an example:

from pdfminer.pdfdocument import PDFDocumentfrom pdfminer.pdfpage import PDFPagefrom pdfminer.pdfparser import PDFParserfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreterfrom pdfminer.converter import PDFPageAggregatorfrom pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFiguredef 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)  # Recursivefp = 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)

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.