Sub topic 1
Know your documents: native PDFs, scans and images
Prerequisites
This chapter assumes you have the following:
- Basic Python, including installing packages with
pip. - Familiarity with JSON.
- Experience calling an LLM API with a prompt and reading the response.
- A basic idea of what a PDF is.
You do not need any OCR or PDF-parsing experience. This chapter covers the first decision in any extraction pipeline: what kind of document you have. Every later choice depends on it. That includes how you get text, whether you need OCR, and what you send to the model.
Why document type comes first
An LLM reads text. A PDF is not text. It is a container that can hold text, images, vector drawings, or any mix of them. Two files that look identical on screen can differ completely inside:
- One stores each character as a text object with a position on the page. You can copy the words out of it.
- The other stores a photograph of a page. The words are only pixels.
If you feed the second kind to a text extractor, you get an empty string. A pipeline that assumes the first kind then fails quietly. The model receives nothing, and it may invent plausible values. The cheapest defense is to classify each document before you process it.
The three document families
Native-text PDFs
A native-text PDF (also called a digital-born PDF) was generated by software such as a word processor, an accounting system or a report generator. The text is stored as characters. Typical examples are invoices emailed by a billing system, exported bank statements and contracts saved from Word.
Properties:
- Text extraction is fast, free and exact. There are no recognition errors.
- The characters are right, but the order and layout may not be. Columns, headers and tables can come out scrambled. Later chapters deal with that.
- Fonts with broken encodings can produce garbage such as
(cid:123)or odd symbols even in a native PDF.
Scanned PDFs
A scanned PDF is a wrapper around one image per page. A scanner, a copier or a phone app produced it. There are no characters in it, only pixels.
Properties:
- A text extractor returns nothing, or nearly nothing.
- You need optical character recognition (OCR), which converts pixels to text, or a vision-capable model that reads the image directly.
- Quality depends on the scan: resolution, skew, shadows, stamps, handwriting and fax noise all reduce accuracy.
Plain images
Photos and screenshots (PNG, JPEG, TIFF, HEIC) are the same problem as scanned PDFs, without the PDF wrapper. Receipts photographed on a table are the common case. They add more variability: perspective distortion, uneven lighting, and a page that fills only part of the frame.
Hybrid documents
Many real files mix the families:
- A native PDF with a scanned signature page appended.
- A scanned PDF that was already run through OCR. It has an invisible text layer placed over the image. It looks like a scan but extracts like a native PDF. The text quality is only as good as the OCR that created it.
- A native PDF with an embedded image of a table or chart. The numbers in the image are not in the text layer.
Because of hybrids, classify per page, not per file.
Comparing the families
| Property | Native-text PDF | Scanned PDF | Image file |
|---|---|---|---|
| Contains characters | Yes | No (unless OCR layer added) | No |
| Text extraction | Direct, exact | Returns empty or near empty | Not applicable |
| Needs OCR or vision | No | Yes | Yes |
| Typical error source | Reading order, tables | Recognition errors, scan quality | Recognition errors, photo quality |
| Relative cost | Lowest | Higher | Higher |
| Speed | Milliseconds per page | Seconds per page | Seconds per page |
Deciding the ingestion path
The decision is made per page, and it is mechanical enough to automate.
The thresholds are heuristics, not standards. A page with fewer than a few dozen characters is suspicious. A page that should be dense, like a one-page invoice, but returns ten characters is almost certainly an image.
Detecting the type in code
The pypdf library gives you the text of each page. Counting the characters per page tells you which pages need another route.
from pypdf import PdfReader
MIN_CHARS = 50 # heuristic: below this, treat the page as image-only
def classify_pages(path):
"""Return a list of (page_number, char_count, kind) for each page."""
reader = PdfReader(path)
results = []
for number, page in enumerate(reader.pages, start=1):
text = page.extract_text() or ""
count = len(text.strip())
kind = "native" if count >= MIN_CHARS else "needs_ocr"
results.append((number, count, kind))
return results
if __name__ == "__main__":
for number, count, kind in classify_pages("invoice.pdf"):
print(f"page {number}: {count} chars -> {kind}")This prints one line per page. A mixed file might look like this:
page 1: 1840 chars -> native
page 2: 1215 chars -> native
page 3: 0 chars -> needs_ocrPage 3 is likely a scanned signature page.
The shorter version below is the quick check for a single-file script. It joins all pages and tests the total length.
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])The whole-file check misses hybrids. A 10-page native PDF with one scanned page passes it, and you lose the content of that page without any warning. Prefer the per-page version in anything that runs unattended.
Edge cases and traps
Text that exists but is useless
A character count only proves that characters exist. These cases pass the check and still fail:
- Broken font encoding. The text layer contains symbols instead of words. Check that the share of ordinary letters and digits is high, or look for
(cid:strings. - Poor OCR layers. A low-quality OCR pass from a copier leaves a text layer full of misrecognitions. The extractor trusts it.
- Boilerplate only. A scanned page with a printed footer in the text layer may reach 50 characters from the footer alone while the body is an image.
A stronger check combines count with a content signal, such as the fraction of alphanumeric characters:
def looks_like_real_text(text, min_chars=50, min_alnum_ratio=0.6):
stripped = "".join(text.split())
if len(stripped) < min_chars:
return False
alnum = sum(ch.isalnum() for ch in stripped)
return alnum / len(stripped) >= min_alnum_ratioEncrypted and protected files
Some PDFs are encrypted. pypdf raises an error or returns nothing until you decrypt with a password. Treat this as a separate failure case and report it. Do not let it look like a scan.
Rotated and mixed-orientation pages
Scans are often upside down or sideways. OCR engines may fail or return rubbish unless the page is rotated first. Some engines detect orientation, and some do not. Check which yours does.
Very large pages and many pages
A 300-page scan costs 300 OCR or vision calls. Count pages before you commit to a route. Chapters later in this tutorial cover cost and long documents.
Don't trust the file extension
A file named .pdf may be an image, and a .jpg may be a PDF. Inspect the file's actual type, for example by its first bytes (%PDF- for PDFs), before routing it.
def sniff_type(path):
with open(path, "rb") as f:
head = f.read(8)
if head.startswith(b"%PDF-"):
return "pdf"
if head.startswith(b"\x89PNG"):
return "png"
if head.startswith(b"\xff\xd8\xff"):
return "jpeg"
return "unknown"Common errors
- Assuming one type for the whole batch. Vendors differ. The same vendor may send native PDFs one month and scans the next.
- Sending empty text to the model. The model has nothing to extract from, so it may hallucinate. Always stop on empty or near-empty input. Do not let it reach the prompt.
- Judging by looking at the file. A scan and a native PDF look the same in a viewer. Test it by trying to select text in the viewer, or by checking programmatically.
- Treating OCR as exact. Native text is exact. OCR text is a prediction. Plan to check OCR-derived values more carefully.
What this means for the rest of the pipeline
The ingestion path sets the quality ceiling for everything downstream. The next chapters build on these routes:
- Native pages go through text extraction, then layout and table handling.
- Image pages go through OCR, or they are sent directly to a vision-capable model.
- Both routes meet at the schema and prompt, where the model turns text into structured fields.
A useful habit is to record the route taken, with the page kind and character count, alongside each extraction result. When a field is wrong later, you can see at once whether the cause was the document type or the model.
Exercise
A 12-page vendor PDF passes your whole-file check (the joined text is 9,000 characters), but the total on page 12 is missing from the extraction. Page 12 is a scanned image of a stamped summary page. What was wrong with the check, and what change fixes it?
Show answer
The check measured the combined text of all pages, so the 11 native pages hid the empty page 12. Classify each page on its own (for example with a minimum character count per page) and route pages below the threshold to OCR or a vision model. Also record the route per page.
Exercise
Give two cases where a page has plenty of extracted characters but is still not safe to send to the model as text, and name one check for each.
Show answer
(1) Broken font encoding gives symbol garbage or (cid: strings. Check the share of alphanumeric characters, or search for (cid:. (2) A poor OCR layer from a copier gives misrecognized words. Compare it with a fresh OCR pass, or spot-check values against the page image. A third valid answer is boilerplate in the text layer, such as a printed footer, that makes up the character count while the body is an image. Check that the expected body content (for example, a total or an invoice number pattern) appears.