Sub topic 1
Know Your Documents: Native PDFs, Scans, and Images
Prerequisites
Assume you know basic Python, JSON, PDFs, and how to call an LLM API. This chapter focuses on choosing the right input path before extraction.
Know Your Documents
A native-text PDF contains an embedded text layer. You can select and copy its words. A scanned PDF contains page images, so text extraction may return little or nothing. An image, such as a JPEG or PNG, has the same limitation.
| Document type | First ingestion step |
|---|---|
| Native-text PDF | Extract the embedded text |
| Scanned PDF or image | Run OCR or send the image to a vision model |
Extracting Text from Native PDFs
Use a PDF parser before using an LLM. For example, pypdf extracts text from many native PDFs:
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("Little text found: try OCR or page images.")
else:
print(text[:500])The character count is only a heuristic. Inspect representative documents and check whether important fields and tables remain understandable.
OCR for Scanned Pages
OCR, or optical character recognition, converts pixels into text. It can misread small fonts, rotated pages, stamps, and handwritten content. Keep the page image when possible so a reviewer or vision model can verify uncertain values.
Layout, Reading Order, and Tables
Plain text can lose columns, indentation, headers, and table relationships. A two-column page may be read down the left column and then down the right, or in an unexpected order. Test extraction on tables that matter to your task. If row and column relationships are essential, preserve coordinates, use a table-aware parser, or provide page images.
Sending Page Images to Vision-Capable Models
A vision-capable model can inspect rendered page images and may preserve visual context better than OCR alone. It costs more and can still miss small text or complex tables. Use it when layout carries meaning, or as a fallback for low-quality OCR.
Designing the Extraction Schema
Define fields before writing the prompt. Make missing values explicit with null, and represent ambiguity instead of forcing guesses. Include types, units, and date formats. For example, an invoice schema might contain vendor, invoice_number, invoice_date, currency, and total.
Exercise
What should you try when a PDF parser returns almost no text?
Show answer
Treat the document as a scan and use OCR or send rendered page images to a vision-capable model.