Sub topic 2
Extracting text from native PDFs
This chapter assumes you can write basic Python, read JSON, and have called an LLM API with a prompt. It also assumes you know a PDF is a file format for fixed-layout pages. You do not need to know PDF internals. The chapter covers what native text extraction does, how to run it with pypdf, how to tell when it has failed, and which errors to expect.
What "native" means
A native-text PDF (also called a digital or born-digital PDF) stores characters as text objects. Each object holds character codes, a font, and a position on the page. Word processors, invoicing systems, and "Save as PDF" exports produce these files.
A scanned PDF stores a photograph of a page. It has no characters at all. A text extractor reads the text objects, so it can only work on a native PDF.
Some files are mixed. A native invoice may carry a scanned stamp, or a scanned report may have a text layer added by earlier OCR (optical character recognition, which converts images of text into characters). Check each page, not just each file.
What a PDF actually stores
A PDF page is a list of drawing instructions. One instruction says, roughly, "draw these glyphs in this font at this x, y position". The format has no built-in idea of a paragraph, a sentence, or a table row. An extractor must rebuild those from positions.
This explains most extraction problems:
- Text is stored in drawing order, which may differ from reading order.
- Spaces are often not stored. The extractor infers them from gaps between glyphs.
- Table cells are separate text objects. Ruled lines are separate graphics.
- Fonts may map character codes to glyphs in a custom way. If the file omits the mapping, the extracted text is garbage even though it looks fine on screen.
Extracting text with pypdf
pypdf is a pure-Python library that reads PDFs and needs no system packages. Install it with pip install pypdf.
from pypdf import PdfReader
reader = PdfReader("invoice.pdf")
pages = [page.extract_text() or "" for page in reader.pages]
text = "\n\n".join(pages)
if len(text.strip()) < 50:
print("Very little text found: the PDF is probably scanned and needs OCR.")
else:
print(text[:500])Points to note in this code:
reader.pagesyields one page object per page, in document order.extract_text()returns a string. It can return an empty string for an image-only page, so theor ""guard keeps the join safe.- Joining with a blank line keeps page boundaries visible in the combined text. You will want those boundaries later, for example when you split a long document.
- The 50-character threshold is a heuristic. It separates "nothing there" from "something there". It is not a measure of quality.
Detecting scans per page
The whole-file check above misses mixed files. A per-page check reports which pages need OCR.
from pypdf import PdfReader
def classify_pages(path, min_chars=50):
reader = PdfReader(path)
result = []
for number, page in enumerate(reader.pages, start=1):
chars = len((page.extract_text() or "").strip())
result.append((number, chars, "text" if chars >= min_chars else "needs_ocr"))
return result
for number, chars, kind in classify_pages("invoice.pdf"):
print(f"page {number}: {chars} chars -> {kind}")Route the needs_ocr pages to the OCR path described in the next chapter. Keep the text pages on the cheap path.
Judging the quality of extracted text
A long string is not proof of good text. Check three things before you build a prompt on it.
Garbled characters
Broken font mappings produce strings such as \x03\x04\x05 or runs of �. A simple ratio test catches many cases.
def looks_sane(text, min_ratio=0.85):
if not text.strip():
return False
good = sum(ch.isalnum() or ch.isspace() or ch in ".,:;-/$%()#@&'\"" for ch in text)
return good / len(text) >= min_ratioThe character set here is tuned for English business documents. Adjust it for other languages, or accept all Unicode letters through isalnum(), which already covers them.
Word order and spacing
Print a page and compare it with the rendered page. Look for three patterns:
- Words glued together (
TotalDue$1,200) or split apart (T otal). Both come from guessed spacing. - Columns interleaved line by line, so a sentence from the left column continues with text from the right column.
- Headers and footers repeated on every page, which add noise to the prompt.
Tables
Tables are the most common failure. A grid like this:
| Item | Qty | Price |
|---|---|---|
| Pens | 10 | 12.00 |
often comes out as one value per line: Item, Qty, Price, Pens, 10, 12.00. The structure is gone. An LLM can often still pair values correctly in a small table, but with many columns or empty cells it will misalign them. The next chapters on layout and on page images cover remedies.
Layout mode
pypdf can try to keep the horizontal layout by padding with spaces.
from pypdf import PdfReader
reader = PdfReader("invoice.pdf")
page = reader.pages[0]
plain = page.extract_text()
laid_out = page.extract_text(extraction_mode="layout")
print(plain[:300])
print("-----")
print(laid_out[:300])Layout mode places text at its horizontal position, so columns and table cells line up in a monospaced view. It costs more tokens because of the padding. It also still guesses at reading order. Compare both modes on a few real documents and keep the one that preserves what your schema needs.
Other libraries
| Library | Strength | Trade-off |
|---|---|---|
| pypdf | Pure Python, easy to install | Weaker layout handling |
| pdfplumber | Word positions, table detection | Slower, more code |
| PyMuPDF | Fast, good reading order, can render pages to images | Different license terms, native dependency |
| pdftotext (poppler) | Fast, strong layout mode | Needs a system install |
Pick one by testing it on your own files. No library wins on every document.
Edge cases
- Encrypted PDFs. Some files have an owner password that only restricts printing.
pypdfmay needreader.decrypt("")before reading. A user password you do not have means you cannot read the file, and you should not try to bypass it. - Malformed files. Exports from unusual tools can raise exceptions inside
extract_text. Catch the exception per page, log the page number, and send that page down the OCR path. - Rotated pages. Text may come out in an odd order. Check
page.rotationwhen results look scrambled. - Hidden text. A PDF can contain white-on-white or off-page text that a human never sees but the extractor returns. This matters for security, covered in a later chapter on prompt injection.
- Ligatures and special characters. Characters such as
fimay appear as a single glyph. Normalize withunicodedata.normalize("NFKC", text)before you compare values to the source. - Hyphenation. A word split across lines (
inter-thennational) stays split. Do not repair it with a blind regex, because real hyphens exist.
import unicodedata
from pypdf import PdfReader
def safe_extract(path):
reader = PdfReader(path)
if reader.is_encrypted:
reader.decrypt("")
out = []
for number, page in enumerate(reader.pages, start=1):
try:
raw = page.extract_text() or ""
except Exception as exc:
print(f"page {number} failed: {exc}")
raw = ""
out.append(unicodedata.normalize("NFKC", raw))
return outKeeping page boundaries
Keep the per-page list instead of only the joined string. Page numbers let you cite where a value came from, process long files in pieces, and send only the failing pages to OCR. Join the pages at the last moment, when you build the prompt.
Common errors
- Empty output treated as an empty document. The page is a scan. Detect it and send it to OCR.
- Assuming file-level type. One scanned page in a native file is missed by a whole-file check.
- Testing on one file. Layout quirks vary by generating software. Test several files from each vendor or source.
- Discarding page numbers. You lose the ability to trace and split.
- Cleaning too aggressively. Removing "extra" whitespace or line breaks can destroy the only hint that separates table columns.
Exercise
A 12-page vendor report returns 9,000 characters from your whole-file check, so it passes. Later you find that the values on pages 7 and 8 are missing from your output. What is the likely cause, and how do you change the code to catch it?
Show answer
Pages 7 and 8 are probably scanned images inside an otherwise native PDF. The whole-file character count is dominated by the text pages, so the check passes. Run the check per page (for example with classifypages), mark pages below the character threshold as needsocr, and send only those pages to OCR.
Exercise
Your extractor returns a table as one value per line, and a model pairs quantities with the wrong items. Name two changes you could try before moving to a different approach.
Show answer
Try extracttext(extractionmode="layout") so columns keep their horizontal alignment, or switch to a library with table detection such as pdfplumber. Comparing the output of each on real documents shows which one preserves the structure.