Keeping columns and lines in order when extracting PDF text

Updated · Tested with Python 3.13, pypdf 7.2.0, PyMuPDF 2.2, pdfplumber 0.11.11, Poppler 25.03

In short

A PDF stores pieces of text with positions, not lines, so each tool rebuilds the order its own way. pypdf and PyMuPDF read a two-column page column by column; pdfplumber and pdftotext -layout read straight across. To fix a tool that reads across, find the empty band between the columns and extract each side separately.

A PDF does not store lines or paragraphs. It stores pieces of text with positions, in whatever order the program that made the file wrote them. Every tool has to rebuild the reading order, and they do not all rebuild it the same way. The examples use report-two-columns.pdf, a page of text in two columns.

What goes wrong

Read straight across, the first two lines of that page come out like this:

Output
Harbor Lane Logistics moved 4,180 kept the increase below the rise in fuel
containers in the third quarter, eight prices.

The first half of each line belongs to the left column and the second half to the right. Nothing in that text tells you where one stops and the other starts.

Tools that read column by column

pypdf and PyMuPDF read this page correctly without any settings: the whole left column, then the right.

Python
import pymupdf

with pymupdf.open("report-two-columns.pdf") as doc:
    for number, line in enumerate(doc[0].get_text().splitlines()[:3], start=1):
        print(number, line)
Output
1 Quarterly operations report
2 Harbor Lane Logistics moved 4,180
3 containers in the third quarter, eight

splitlines() is also the answer to reading a PDF line by line: both libraries return one line of the page per line of text.

PyMuPDF works in blocks, which are usually paragraphs, and you can ask for them with their positions:

Python
import pymupdf

with pymupdf.open("report-two-columns.pdf") as doc:
    for x0, y0, x1, y1, text, *_ in doc[0].get_text("blocks")[:3]:
        print(round(x0), round(y0), round(x1), round(y1), text.replace("\n", " ")[:50])
Output
68 78 360 105 Quarterly operations report
68 123 282 218 Harbor Lane Logistics moved 4,180 containers in th
68 230 266 293 Average time at the gate fell from 41 minutes to 3

Be careful with get_text(sort=True) here. It sorts by position from top to bottom, which is what you want for labels and values on one line, and exactly what mixes two columns together.

Tools that read across: find the gap, then cut

pdfplumber reads across the page. The fix is to find the empty band between the columns and read each side on its own. A column gap is a range of x that no word of the body text crosses:

Python
import pdfplumber

with pdfplumber.open("report-two-columns.pdf") as pdf:
    page = pdf.pages[0]
    words = [w for w in page.extract_words() if w["top"] > 110]   # below the title

    covered = [0] * int(page.width)
    for w in words:
        for x in range(int(w["x0"]), min(int(w["x1"]) + 1, len(covered))):
            covered[x] += 1

    left = min(int(w["x0"]) for w in words)
    right = max(int(w["x1"]) for w in words)
    gaps, start = [], None
    for x in range(left, right + 1):
        if covered[x] == 0 and start is None:
            start = x
        if covered[x] and start is not None:
            gaps.append((start, x))
            start = None
    print(gaps)
Output
[(284, 311)]

One gap, from x = 284 to x = 311. Cut in the middle of it:

Python
    cut = (gaps[0][0] + gaps[0][1]) / 2
    left_text = page.crop((0, 0, cut, page.height)).extract_text()
    right_text = page.crop((cut, 0, page.width, page.height)).extract_text()

Two details matter. The title is left out when looking for the gap, because it runs across both columns and would hide it. And a heading that crosses the cut is split in two, so read titles separately from the body.

From the command line

pdftotext, from the free Poppler tools, has three modes that behave differently on this page:

CommandResult on the two-column page
pdftotext file.pdf -Paragraphs, but not always in column order
pdftotext -layout file.pdf -Both columns side by side, with spaces between them
pdftotext -raw file.pdf -The order the file stores, here column by column

When rows matter more than columns

Reading across is not always wrong. For a page of labels and values, or a table, each row is one record, and you want the label and its value on one line. That is the opposite need from a two-column article, and it is why no single setting is right for every page.

100sands reads row by row: /v1/text returns each line of the page as one line, which keeps a label with its value, separated by a tab. Like pdfplumber, it reads a two-column article straight across, with a tab between the columns on each line. It does not return positions, so for pages like that, crop the page with a library as shown above.

Questions

How do I extract text from a PDF line by line in Python?

Call extract_text() in pypdf or get_text() in PyMuPDF and split the result with splitlines(). Each line of the page is one line of the string.

Why are two columns of my PDF mixed together?

Your tool sorts text by its height on the page and reads across the full width, so line one of the left column is followed by line one of the right. Use a tool that reads column by column, or crop the page at the gap between the columns.

Should I use sort=True in PyMuPDF?

Use it for pages of labels and values or tables, where each row is one record. Do not use it for pages with several columns of running text, because it merges the columns.

Does pdftotext keep columns?

With -layout it keeps the columns side by side, separated by spaces, which preserves the look of the page but not the reading order. With -raw it returns the order stored in the file.

Try it on your own documents

A free plan every month, no credit card. See the PDF to text API.

Start free