Getting clean PDF text for LLMs and RAG
Updated · Tested with Python 3.13, PyMuPDF 2.2
In short
Give a language model text in reading order, with page numbers, and with nothing silently missing. Check multi-column pages, because columns read across produce false sentences. Find pages with no text, because scans return an empty string and no error. Cut the text into chunks at paragraph ends, not every N characters, and keep tables out of the running text.
A language model can only answer from the text you hand it. If two columns are mixed together, a table is flattened into a run of numbers, or a scanned page comes through empty, the model works from damaged input and gives confident answers anyway. Most "the model made it up" problems with documents start before the model, in how the text was taken out of the file.
What good input looks like
- In reading order. Sentences are whole, and columns are not woven together.
- With page numbers. So an answer can point to where it came from.
- Without repeated clutter. Headers, footers and page numbers repeated on every page crowd out the content.
- Complete. Scanned pages are read, not skipped.
- In pieces that make sense alone. A chunk that starts mid-sentence is hard to find and hard to use.
Step 1: text with page numbers
Keep the page with the text from the start; you cannot recover it later.
import pymupdf
def pages_text(path):
with pymupdf.open(path) as doc:
return [(number, page.get_text()) for number, page in enumerate(doc, start=1)]
for number, text in pages_text("report-two-columns.pdf"):
print(number, len(text), repr(text[:60]))1 870 'Quarterly operations report\nHarbor Lane Logistics moved 4,18'Step 2: check the reading order
Our sample, report-two-columns.pdf, has two columns. Read across the page, its first line becomes:
Harbor Lane Logistics moved 4,180 kept the increase below the rise in fuelTwo half-sentences from different paragraphs, joined into something that looks like a sentence. A model will happily reason about it. PyMuPDF and pypdf read this page column by column; pdfplumber does not. Read one multi-column page by eye before you index a whole collection. Keeping columns and lines in order has the fix.
Step 3: find the pages with no text
A scanned page returns an empty string, and an empty string raises no error. In a collection of contracts or invoices some pages are always scans, and they vanish silently.
empty = [number for number, text in pages_text("mixed-text-and-scan.pdf") if not text.strip()]
print(empty)[2]Page 2 of mixed-text-and-scan.pdf is a scan. Send pages like that through OCR, as in how to OCR a scanned PDF in Python, or count them and say so; do not index a document as if it were complete.
Step 4: cut into chunks at paragraph ends
For retrieval, text is cut into chunks, and each chunk is searched for on its own. Cutting every N characters splits sentences in half. Cut at paragraph ends, and fill each chunk up to a size limit.
PyMuPDF returns blocks, which are usually paragraphs:
import pymupdf
def chunks(path, max_chars=600):
result = []
with pymupdf.open(path) as doc:
for number, page in enumerate(doc, start=1):
paragraphs = [b[4].replace("\n", " ").strip() for b in page.get_text("blocks") if b[4].strip()]
current = ""
for paragraph in paragraphs:
if current and len(current) + len(paragraph) > max_chars:
result.append({"page": number, "text": current})
current = ""
current = (current + " " + paragraph).strip()
if current:
result.append({"page": number, "text": current})
return result
parts = chunks("report-two-columns.pdf")
print(len(parts), [len(part["text"]) for part in parts])
print(parts[1]["text"][:90])2 [501, 367]
Two customers moved their storage contracts to yearly terms. Together they fill a third ofTwo chunks, each made of whole paragraphs, each with its page number. The second starts at the beginning of a paragraph, not in the middle of one.
Chunk size is a trade. Small chunks are found precisely and carry little context; large ones carry context and match loosely. A few hundred to a couple of thousand characters is the usual range; test with your own questions.
Step 5: do not flatten tables
A table turned into a stream of words loses which number belongs to which row and column. Options, from simple to thorough:
- extract tables separately and give them to the model as rows, one per line with the column names, as in how to extract tables from a PDF;
- keep the layout text (
pdftotext -layout), which holds columns in place with spaces; - for facts you need exactly, such as totals and dates, do not ask the model to read them at all: extract them as fields and pass them as data.
Text or Markdown?
Markdown is popular as model input because headings and tables survive. It is worth having when your documents have real structure. But a converter has to guess that structure from font sizes and positions, and a wrong guess is worse than plain text. For reports and letters, clean text in reading order with page numbers gets you most of the way.
Where 100sands fits
100sands returns the text of a PDF or HTML file from one call, with lines in reading order in every language, right-to-left and complex scripts included, a tab between cells on a line, and a form feed (\f) between pages, so the page numbers of step 1 come from splitting on it. The result is the same every time for the same file, which keeps an index stable when you rebuild it.
Three things to know before you use it for this. It returns plain text, not Markdown. It reads each page line by line across its full width, so for pages set in two or more columns use a column-aware reader such as PyMuPDF, as in step 2. And it does not do OCR: a file with no text is refused with status 422 and the code NO_TEXT_IN_FILE, and in a file that mixes text and scanned pages the scanned ones come back blank, so step 3 still applies. For single-column documents that contain text, one call does the job:
curl -s https://api.100sands.com/v1/text \
-H "Authorization: Bearer $SANDS_API_KEY" \
-F [email protected] | jq -r .text