Before a PDF reaches a model, the decision that matters is the shape it takes in the context window. Multimodal models read page images directly today, so the content of a PDF is not the obstacle — preparation is. Which part travels the text channel, which part travels the visual channel, and what each side should look like.
Routing by document type is the common practice now. Clean electronic documents go through deterministic parsing and come back as structured text with headings, tables, and page numbers. Scans, chart-heavy pages, and complex layouts go to a vision model, where the page image is the input. The two channels are not mutually exclusive, and a sound pipeline usually keeps both: the text channel for exact matching, computation, and citable locations, the visual channel for charts and spatial relationships.
| Channel | Material | Suits | Cost and risk |
|---|---|---|---|
| Text | Structured Markdown, row-and-column data | Retrieval, exact matching, citation locations | Cheap and controllable; structure can be lost on complex layouts |
| Visual | Page images | Charts, stamps, two-column and complex layouts | More expensive per page; numbers can be read wrong while reading smoothly |
| Hybrid | Both | Most enterprise documents | Needs evaluation and cross-checking |
This article uses Spire.PDF to prepare the material for both channels in one pass: read each page's size and text layer, pull document metadata, convert the whole file to Markdown, pull tables out as rows and columns, and keep page images for a vision model. It uses Spire.PDF for Python, installed with:
pip install spire.pdf
PdfToMarkdownConverter is available from 11.6.1, and MarkdownOptions.IgnoreImage from 11.12.1.
The Object Model
| Object | Role | Members used in this article |
|---|---|---|
PdfDocument |
The document |
LoadFromFile, Pages, DocumentInformation, SaveAsImage
|
PdfPageBase |
A page |
Size, Canvas
|
PdfTextExtractor / PdfTextExtractOptions
|
Per-page text |
ExtractText, ExtractArea
|
PdfToMarkdownConverter / MarkdownOptions
|
Whole-document Markdown |
ConvertToMarkdown, IgnoreImage
|
PdfTableExtractor / Utilities_PdfTable
|
Table structure |
ExtractTable, GetRowCount, GetColumnCount, GetText
|
The sample input is a two-page quarterly brief: page one carries a title band, three KPI cards, and a regional revenue table; page two carries a product table, a bar chart, and the priorities for next quarter. The code below runs against that file, in order.
Probing the Skeleton: What Kind of File Is This
The first pass is observation: how many pages, how large, whether a text layer exists, what the metadata says. That information decides the route — a document with a text layer can be extracted directly, while a scan needs image recognition first.
from spire.pdf import *
from spire.pdf.common import *
doc = PdfDocument()
doc.LoadFromFile("quarterly-brief.pdf")
print("pages:", doc.Pages.Count)
for i in range(doc.Pages.Count):
page = doc.Pages.get_Item(i)
extractor = PdfTextExtractor(page)
text = extractor.ExtractText(PdfTextExtractOptions())
print("page %d size: %.0f x %.0f | text chars: %d" % (
i + 1, page.Size.Width, page.Size.Height, len(text)))
info = doc.DocumentInformation
print("title:", info.Title)
print("author:", info.Author)
print("subject:", info.Subject)
print("keywords:", info.Keywords)
doc.Close()
pages: 2
page 1 size: 595 x 842 | text chars: 2169
page 2 size: 595 x 842 | text chars: 1317
title: Q3 2026 Business Brief
author: Sales & Operations
subject: Q3 performance data and next-quarter priorities
keywords: business brief,quarterly,regional detail,internal
Both pages are A4 (595 × 842 pt) and both carry a text layer of roughly two thousand characters, which means this is a born-digital document rather than a scan. The title, author, subject, and keywords in DocumentInformation are worth carrying along as context: a retrieval hit that includes them matches the question more often.
What Plain Text Extraction Actually Returns
Text extraction returns a content stream, not paragraphs. On page one, the three KPI labels come out as one line, their three numbers as another; each table row is a horizontally stretched sequence of fragments; and the footer with its page count and department name trails the body copy.
from spire.pdf import *
from spire.pdf.common import *
doc = PdfDocument()
doc.LoadFromFile("quarterly-brief.pdf")
for i in range(doc.Pages.Count):
page = doc.Pages.get_Item(i)
extractor = PdfTextExtractor(page)
text = extractor.ExtractText(PdfTextExtractOptions())
lines = [line for line in text.split("\n") if line.strip()]
header_hits = sum(1 for line in lines if "Q3 2026 Business Brief" in line)
footer_hits = sum(1 for line in lines if "Page" in line)
print("--- page %d | %d chars | %d non-empty lines" % (
i + 1, len(text), len(lines)))
print(" header repeats: %d | footer repeats: %d" % (header_hits, footer_hits))
doc.Close()
--- page 1 | 2169 chars | 22 non-empty lines
header repeats: 1 | footer repeats: 1
--- page 2 | 1317 chars | 13 non-empty lines
header repeats: 1 | footer repeats: 1
Compare that with the rendered page. The table's header row and its data rows are separate strings in the character stream, and the model has to guess that "East" belongs to "128" and "1,365.00". The header and footer repeat once per page and read as part of the body. That noise is baked into the extraction path, and the fix is a different path rather than a cleverer prompt.
Converting the Whole Document to Markdown
PdfToMarkdownConverter follows the visual structure of the document: section headings become bold, body copy stays in paragraphs, and tables come back as pipe tables with a separator row. This brief converts to 2,580 characters containing 10 pipe-table rows.
from spire.pdf import *
from spire.pdf.common import *
converter = PdfToMarkdownConverter("quarterly-brief.pdf")
converter.MarkdownOptions.IgnoreImage = True
converter.ConvertToMarkdown("quarterly-brief.md")
with open("quarterly-brief.md", encoding="utf-8") as fp:
markdown = fp.read()
print("markdown chars (IgnoreImage=True):", len(markdown))
print("pipe table rows:", markdown.count("|:---"))
print("base64 images:", markdown.count("data:image"))
markdown chars (IgnoreImage=True): 2580
pipe table rows: 10
base64 images: 0
The pipe table is the most useful part of the conversion: headers and data rows are separated by |, so the model reads a table it can compare across columns instead of two piles of fragments. One detail is worth noticing — + and - are special characters in Markdown, so the converter writes +18.2% as \+18.2%. That is standard escaping and models read it correctly, but string comparison against the original text has to account for it.
Images: Keep Them or Drop Them
Whether a chart should enter the context window depends on how much it carries. IgnoreImage decides: set it to True and images are skipped, leaving text only; set it to False and each image is inlined into the Markdown as base64 data.
from spire.pdf import *
from spire.pdf.common import *
converter = PdfToMarkdownConverter("quarterly-brief.pdf")
converter.MarkdownOptions.IgnoreImage = False
converter.ConvertToMarkdown("quarterly-brief-with-images.md")
with open("quarterly-brief-with-images.md", encoding="utf-8") as fp:
with_images = fp.read()
with open("quarterly-brief.md", encoding="utf-8") as fp:
markdown = fp.read()
print("markdown chars (IgnoreImage=False):", len(with_images))
print("base64 images:", with_images.count("data:image"))
print("size ratio: %.1fx" % (len(with_images) / len(markdown)))
markdown chars (IgnoreImage=False): 27552
base64 images: 1
size ratio: 10.7x
A single bar chart pushes the text from 2,580 characters to 27,552 — an order of magnitude. That base64 payload adds nothing for a text-only model and still consumes the token budget. The workable split is deliberate: Markdown travels the text channel, the page image goes to a vision model, and each goes where it carries weight.
Extracting Tables as Structure
Markdown conversion already restores tables, but when the fields need to be under your own control, PdfTableExtractor pulls them out by row and column. This brief has one table per page, 6×5 and 5×5, and both come out complete before being assembled into a Markdown pipe table.
from spire.pdf import *
from spire.pdf.common import *
doc = PdfDocument()
doc.LoadFromFile("quarterly-brief.pdf")
extractor = PdfTableExtractor(doc)
blocks = []
for page_index in range(doc.Pages.Count):
tables = extractor.ExtractTable(page_index)
print("page %d tables: %d" % (page_index + 1, len(tables)))
for table in tables:
rows = table.GetRowCount()
cols = table.GetColumnCount()
print(" table %dx%d" % (rows, cols))
grid = [[table.GetText(r, c) for c in range(cols)] for r in range(rows)]
blocks.append((page_index + 1, grid))
lines = []
for page_no, grid in blocks:
lines.append("| " + " | ".join(grid[0]) + " |")
lines.append("|" + "|".join([" --- "] * len(grid[0])) + "|")
for row in grid[1:]:
lines.append("| " + " | ".join(row) + " |")
lines.append("")
with open("tables.md", "w", encoding="utf-8") as fp:
fp.write("\n".join(lines) + "\n")
print("table blocks:", len(blocks))
doc.Close()
page 1 tables: 1
table 6x5
page 2 tables: 1
table 5x5
table blocks: 2
One observation is worth carrying into a pipeline: whether a table gets detected depends on how it is drawn. The tables in this brief carry vertical grid lines and both were pulled out intact; the same content drawn with horizontal rules only degrades into lines of text. Report-style PDFs usually have grid lines, while tables in contracts and papers often do not. For those, exporting the table page as an image and handing it to a vision model works, with the row-and-column structure here serving as the reference.
Page Images: The Half That Goes to a Vision Model
A page image is how the layout reaches a vision model unchanged. SaveAsImage exports one PNG per page, and an A4 page comes out at 794 × 1123 pixels at 96 DPI, enough for a model to read the tables and the chart.
import os
from PIL import Image
from spire.pdf import *
from spire.pdf.common import *
doc = PdfDocument()
doc.LoadFromFile("quarterly-brief.pdf")
os.makedirs("pages", exist_ok=True)
for i in range(doc.Pages.Count):
path = os.path.join("pages", "page_%d.png" % (i + 1))
doc.SaveAsImage(i).Save(path)
with Image.open(path) as im:
print("saved: page_%d.png | %d x %d px" % (i + 1, im.width, im.height))
doc.Close()
saved: page_1.png | 794 x 1123 px
saved: page_2.png | 794 x 1123 px
Page images and Markdown are complementary: Markdown carries what is searchable, computable, and quotable, while the image carries spatial relationships — the shape of a bar chart, the position of a stamp, the visual grouping of a table. With both in the context, the model reads the content and sees the layout.
API Quick Reference
| Class | Role |
|---|---|
PdfDocument |
Load the document, walk pages, read metadata, export pages |
PdfPageBase |
Page size and canvas |
PdfTextExtractor |
Extract page text, optionally from a region |
PdfToMarkdownConverter |
Convert a document to Markdown |
PdfTableExtractor |
Extract table structure per page |
| Method / Property | Owner | Purpose |
|---|---|---|
LoadFromFile(path) |
PdfDocument |
Load a PDF file |
Pages.Count / Pages.get_Item(i)
|
PdfDocument |
Access pages by index |
DocumentInformation |
PdfDocument |
Read title, author, subject, keywords, and other metadata |
SaveAsImage(i) |
PdfDocument |
Export a page as an image |
Size |
PdfPageBase |
Page width and height in points |
ExtractText(options) |
PdfTextExtractor |
Extract the text of a page |
ExtractArea |
PdfTextExtractOptions |
Restrict extraction to a rectangle |
ConvertToMarkdown(path) |
PdfToMarkdownConverter |
Write the Markdown file |
IgnoreImage |
MarkdownOptions |
Whether images are skipped |
ExtractTable(pageIndex) |
PdfTableExtractor |
Tables found on the given page |
GetRowCount() / GetColumnCount() / GetText(r, c)
|
Utilities_PdfTable |
Table dimensions and cell values |
Boundaries and Trade-offs
This flow repairs data shape; it does not replace business rules. Whether headers and footers are dropped, whether a total row counts, whether an amount is read raw or as displayed — those are caller decisions, and the places where the code tests strings are exactly where those rules live. A scan has no text layer and needs its pages rendered to images before OCR; Free Spire.PDF for Python caps documents at 10 pages and covers only the first 3 pages for image conversion, with the commercial edition lifting both limits.
The two channels also fail differently, which matters when choosing between them. Deterministic parsing fails loudly — garbled or empty text that surfaces immediately. A vision model can fail quietly instead, reading a table's figures fluently while pointing at the wrong cell. Where amounts, part numbers, or dates are involved, keeping a deterministic extraction alongside for cross-checking is safer than running on a single channel.
The conclusion worth keeping is that whether a model can read a given PDF is rarely the bottleneck; what the material became before it arrived is. The text channel needs structure — headings, tables, page numbers — and the visual channel needs layout — charts, stamps, columns. Each has its own way of being produced.






Top comments (0)