Sub topic 2
Extracting text from native PDFs
This chapter assumes you can run Python, install packages with pip, and read basic JSON. It builds on the previous chapter's split between native-text PDFs and scans. Here you extract text from the native kind and check whether the result is usable.
What "native" means for extraction
A native-text PDF stores characters as text objects, each with a font and a position on the page. A text library can read those objects directly, so no image analysis is needed. Extraction is fast, cheap, and exact: the characters you get are the characters in the file.
A scanned PDF stores each page as a picture. A text library finds nothing to read, so the result is empty or nearly empty. That difference gives you a simple test.
Extract text with pypdf
Install the library with pip install pypdf. The code below reads every page, joins the pages, and treats a near-empty result as a sign of a scan.
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])Three details matter here:
extract_text()can return an empty string orNoneon some pages, soor ""keeps the join from failing.- The
\n\nseparator keeps page boundaries visible, which helps later when you split long documents. - The 50-character threshold is a heuristic. Tune it to your documents.
How the pipeline decides
Common errors
Text that exists is not always text that is good. Check these cases before you trust the output.
| Symptom | Likely cause | What to do |
|---|---|---|
| Empty or tiny output | Scanned pages | Route to OCR |
| Scrambled words or odd symbols | Fonts with custom encodings | Try another library, or render the page and use OCR |
| Columns interleaved line by line | Multi-column layout read in file order | Inspect the output and try layout-aware extraction |
| Table cells run together | Tables have no text structure, only positions | Handle tables as a separate step |
| Mixed pages: some text, some empty | Partly scanned document | Check each page, not only the total |
The last row is easy to miss. A 40-page file with one text page and 39 scanned pages can pass a whole-document length check. Measure the text length per page instead:
from pypdf import PdfReader
reader = PdfReader("invoice.pdf")
for number, page in enumerate(reader.pages, start=1):
length = len((page.extract_text() or "").strip())
status = "ok" if length >= 50 else "needs OCR"
print(f"Page {number}: {length} characters ({status})")Judge the result by reading it
Print a sample and read it yourself. Ask three questions:
- Are the words complete and in a sensible order?
- Do the fields you need, such as invoice number or total, appear next to their labels?
- Are numbers intact, with no missing digits or split decimals?
If the answers are yes, the text is ready for the prompt. If the layout is damaged, an LLM may still cope with mild disorder, but it can pair a label with the wrong value. The next chapters cover scans and tables.
Exercise
A 30-page contract passes your whole-document check with 12,000 characters, yet the model returns null for fields that appear on pages 20 to 30. What is a likely cause, and how do you confirm it?
Show answer
Pages 20 to 30 may be scanned images, with the other pages carrying all the text. Confirm it by printing the extracted character count for each page. Pages with near-zero counts need OCR.