Sub topic 11
Deciding between text extraction, page images and native PDF
This chapter helps you pick one of three ways to give a PDF to a multimodal model. It assumes you can already send an image and a native PDF in a request, know that PDFs are processed as text plus page visuals, and understand token costs and context windows. If any of that is unfamiliar, review the earlier chapters on PDF input and token cost first.
The three options
A PDF can reach a model in three forms.
- Text extraction. You pull the text out of the file with a library, then send it as ordinary text. The model never sees the layout or any pictures.
- Page images. You render each page to a PNG or JPEG and send the pages as images. The model sees the layout but has to read every character visually.
- Native PDF. You send the file as a document block. The provider typically extracts the text and also renders the pages, so the model receives both. Check your provider's documentation for the details of what it does.
Each option moves work and risk to a different place. Extraction is cheap and exact for text, but it throws away structure. Page images keep everything visible, but cost more and can misread small print. Native PDF is the simplest to code and often the most complete, but you give up control over what the provider does with the file.
Know what kind of PDF you have
The first decision depends on the file itself. PDFs fall into two groups.
- Digital PDFs contain real text objects. You can select and copy text in a viewer. Most exported reports, invoices from billing software and articles are digital.
- Scanned PDFs are pictures of pages. There is no text layer, or there is a low-quality one added by OCR (optical character recognition, software that turns pictures of text into text).
Text extraction works on digital PDFs and returns nothing useful on scans. Page images and native PDF work on both. This check is cheap, so run it before anything else.
import fitz # PyMuPDF
def text_layer_report(pdf_path, min_chars=50):
"""Return (page_number, character_count, has_text) for each page."""
report = []
with fitz.open(pdf_path) as doc:
for number, page in enumerate(doc, start=1):
text = page.get_text().strip()
report.append((number, len(text), len(text) >= min_chars))
return report
for number, chars, has_text in text_layer_report("report.pdf"):
print(f"page {number}: {chars} characters, text layer: {has_text}")A page with almost no characters is probably a scan, a full-page image or a diagram. The threshold of 50 is a rough guess. Adjust it for your documents.
What each option loses
Text extraction
Extraction libraries return a stream of characters, and several things can go wrong.
- Reading order can break on multi-column pages. Two columns may be interleaved line by line.
- Tables become rows of loose words. The link between a number and its column header is often lost.
- Charts, photos and diagrams vanish. Only their captions survive.
- Headers, footers and page numbers appear in the middle of your text.
- Some PDFs use fonts with broken character maps, so the text comes out as garbage even though a viewer displays it correctly.
Page images
Rendering keeps layout, tables, charts and handwriting. The costs are different.
- Every page consumes image tokens, whether it holds a paragraph or a single line.
- Small text can be misread. Resolution matters here, because a page rendered at 72 DPI may have unreadable footnotes. Rendering at 150 DPI is a common starting point, and then the image is usually scaled down to the provider's maximum size anyway.
- Numbers and identifiers can be misread, for example an 8 as a 3 or a 0 as an O. The model reads pixels, not the stored characters.
Native PDF
The provider handles both channels, which covers most cases. The trade-offs are these.
- You pay for both text tokens and image tokens for each page.
- Limits on file size and page count apply, and they differ between providers. Check them in the current documentation.
- Some providers or models do not accept PDFs at all, or accept them only through a particular API or upload route.
- You cannot see or tune the extraction step.
Comparison
| Factor | Text extraction | Page images | Native PDF |
|---|---|---|---|
| Works on scanned PDFs | No | Yes | Yes |
| Sees charts and layout | No | Yes | Yes |
| Exact characters for digital text | Yes | No, read from pixels | Yes, from the text layer |
| Token cost per page | Lowest | Medium to high | Highest, text plus image |
| Code you write | Library call | Render, resize, encode | Encode and send |
| Control over input | Full | Full | Little |
| Needs provider PDF support | No | No | Yes |
A decision procedure
Work through these questions in order and stop at the first that applies.
- Does the provider or model lack PDF support? Use text extraction or page images.
- Is the document scanned, handwritten or mostly pictures? Use native PDF, or page images if you want control over resolution and which pages are sent.
- Is it a digital PDF where only the words matter? Use text extraction. Examples are contracts, articles and transcripts. It is the cheapest and gives exact characters.
- Does meaning depend on layout, tables or charts? Use native PDF, or page images for just the pages that need it.
- Is the document long? Do not send everything. Select the relevant pages first, then apply the rules above to those pages.
A hybrid approach
Often the best result mixes methods. Extract text for every page, then send page images only for pages where the text is thin or where a table or figure appears. This keeps the cost near the text-only level and uses vision where it pays off.
import base64
import fitz # PyMuPDF
def build_content(pdf_path, min_chars=200, dpi=150):
"""Build content blocks: text for text-rich pages, an image for the rest."""
blocks = []
with fitz.open(pdf_path) as doc:
for number, page in enumerate(doc, start=1):
text = page.get_text().strip()
if len(text) >= min_chars and not page.get_images():
blocks.append({"type": "text", "text": f"[Page {number}]\n{text}"})
else:
png = page.get_pixmap(dpi=dpi).tobytes("png")
data = base64.standard_b64encode(png).decode("utf-8")
blocks.append({"type": "text", "text": f"[Page {number}]"})
blocks.append(
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": data,
},
}
)
return blocks
content = build_content("report.pdf")
content.append({"type": "text", "text": "Summarize the key findings in this report."})
print(f"{len(content)} content blocks")The block format above follows the Anthropic Messages API. For another provider, change the image block to that provider's shape. Each page is labeled with a text block, so the model can cite page numbers in its answer.
The page.get_images() test sends any page that embeds a picture as an image. That is a heuristic. A logo on every page would trigger it, so you may want to ignore small images in a real pipeline.
Edge cases
- Mixed documents. A report may have digital body pages and scanned appendix pages. Decide per page, not per file, as the hybrid code does.
- Bad OCR layers. A scan that someone ran through OCR years ago has a text layer, so a character count says it is fine. If the text looks wrong, compare it with the rendered page. Native PDF input may then give the model two conflicting versions, so test it.
- Password-protected or damaged files. Extraction libraries and providers both fail on these, usually with different errors. Handle them before the decision step.
- Very large pages. Posters, maps and engineering drawings exceed the provider's image size limit and get shrunk, which loses fine detail. Tile the page into sections and send each tile as an image.
- Page limits. If a provider caps pages per request, split the file and run several requests, then combine the results.
- Repeated questions. If you ask many questions about one document, the cost of resending it adds up. Cache the extracted text, or use the provider's file upload or prompt caching features where they exist.
Measure instead of guessing
You can compare the options on your own files in a few minutes. Take ten representative documents and a question set with known answers. Run each through all three methods. Record accuracy, input tokens and latency. The numbers often show that the cheap method is good enough for most of your files and that a few document types need vision.
Exercise
A company receives two kinds of PDFs. Type A is a digital, 40-page legal contract with plain paragraphs. Type B is a scanned, 3-page handwritten delivery form with a table. Which method would you choose for each, and why?
Show answer
Type A: text extraction. The text layer is exact, the layout adds little meaning, and extraction costs far fewer tokens than 40 page images or a native PDF. Type B: native PDF or page images. A scan has no text layer, so extraction returns nothing, and the model needs to see the handwriting and the table layout. With only 3 pages, the extra cost is small. Page images give you control over resolution if handwriting is hard to read.
Exercise
Your hybrid pipeline sends a page as an image whenever page.get_images() is not empty. Every page of a report has a small company logo, so every page is sent as an image and costs rise. How would you fix it?
Show answer
Filter the images by size before deciding. For example, use page.getimageinfo() or the image rectangles to ignore pictures below a minimum width and height, or smaller than some fraction of the page area. Then a page is sent as an image only when it contains a large figure, or when its text is too short. Check the change against your test set to confirm that no real charts are skipped.