Search code examples
pythonpython-3.xpdftextpdfminer

Keep Layout of extracted text in pdfminer.six python


I want to extract the text of this pdf: https://github.com/pdfminer/pdfminer.six/files/1887670/Wochenkarte-KW-15-Neu.pdf

When I extract the text using this code:

def convert_pdf_to_txt(path):
    resource_manager = PDFResourceManager()
    device = None
    try:
        with StringIO() as string_writer, open(path, 'rb') as pdf_file:
            device = TextConverter(resource_manager, string_writer, codec='utf-8', laparams=LAParams())
            interpreter = PDFPageInterpreter(resource_manager, device)

            for page in PDFPage.get_pages(pdf_file, maxpages=1):
                interpreter.process_page(page)

            pdf_text = string_writer.getvalue()
    finally:
        if device:
            device.close()
    return pdf_text

The text corresponds not to the text layout of the pdf. Current Result:

Montag 09.04.2018 
Menü 1 

Kl. Salat 


Menü 2 

Kl. Salat 

Seelachs-Spinat-Türmchen mit Spinat-
Masalla-Sauce und Reis 
Currywurst mit Pommes 

Expected Result:

Montag 09.04.2018 
Menü 1 

Kl. Salat Seelachs-Spinat-Türmchen mit Spinat-Masalla-Sauce und Reis 

Menü 2 

Kl. Salat Currywurst mit Pommes 

What do I do wrong or am I missing something else?


Solution

  • The key is giving another linemargin in LAParams:

    LAParams(line_margin=0.1)
    

    My line looks now like this:

    device = TextConverter(resource_manager, string_writer, codec='utf-8', laparams=LAParams(line_margin=0.1))
    

    Credits to Tim