Sub topic 10
Rendering PDF pages as images
This chapter assumes you can call a vision-capable LLM API with an image content block, that you know how base64 encoding works, and that you have read the earlier chapters on image preprocessing and on sending a PDF natively. Here you will turn each page of a PDF into an image yourself, and then send those images like any other.
Why render pages yourself
Native PDF input is convenient, but it is not always available or suitable. Rendering pages to images gives you control in these cases:
- The provider or model you use does not accept PDF input.
- The native route enforces page-count or file-size limits that your document exceeds.
- You need only a few pages from a long document, and you want to pay for only those pages.
- You want to control resolution, so you can trade cost against legibility of small print.
- You want to crop to a region, such as a table or a stamp, before sending.
Rendering is also the common fallback when a PDF has an unusual structure that the provider's own pipeline handles poorly.
How rendering works
A PDF page is a set of drawing instructions: text with fonts, vector lines, and embedded images. A renderer interprets those instructions and produces a grid of pixels. The size of that grid depends on the resolution you choose, measured in DPI (dots per inch). A standard US Letter page is 8.5 by 11 inches, so:
| DPI | Pixel size of a Letter page | Typical use |
|---|---|---|
| 72 | 612 x 792 | Thumbnails, rough layout checks |
| 150 | 1275 x 1650 | Default for most reading tasks |
| 200 | 1700 x 2200 | Small print, dense tables |
| 300 | 2550 x 3300 | Rarely needed; usually gets downscaled anyway |
Higher DPI does not always help. Most providers shrink large images before the model sees them, so a 300 DPI render may be reduced to roughly the same detail as a 200 DPI one, while you still pay for the larger upload. Check your provider's documentation for its maximum image dimensions and for how it computes token cost.
Rendering with PyMuPDF
PyMuPDF (imported as fitz) renders pages without needing external programs. Install it with pip install pymupdf. The function below renders a chosen set of pages and returns PNG bytes.
import fitz # PyMuPDF
def render_pages(pdf_path, dpi=150, pages=None):
"""Render PDF pages to PNG bytes.
pages is an optional list of zero-based page indexes.
If it is None, every page is rendered.
"""
results = []
with fitz.open(pdf_path) as doc:
indexes = range(len(doc)) if pages is None else pages
for i in indexes:
if i < 0 or i >= len(doc):
raise IndexError(f"Page {i} is out of range (0 to {len(doc) - 1})")
pix = doc[i].get_pixmap(dpi=dpi)
results.append(pix.tobytes("png"))
return results
pngs = render_pages("report.pdf", dpi=150, pages=[0, 1, 2])
print(f"Rendered {len(pngs)} pages, first is {len(pngs[0])} bytes")Page indexes in PyMuPDF start at zero. When you talk to the model or to users, convert to one-based page numbers, or the model's answer ("see page 3") will not match the file.
Sending the rendered pages
Each PNG becomes one image block. The sketch below uses the Anthropic Messages API and labels every page with a short text block so the model can cite page numbers.
import base64
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
def pages_to_blocks(png_list, first_page_number=1):
"""Build alternating label and image blocks, one pair per page."""
blocks = []
for offset, png in enumerate(png_list):
number = first_page_number + offset
blocks.append({"type": "text", "text": f"Page {number}:"})
blocks.append(
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": base64.standard_b64encode(png).decode("utf-8"),
},
}
)
return blocks
blocks = pages_to_blocks(pngs)
blocks.append(
{
"type": "text",
"text": "Summarize the key findings. Cite the page number for each one.",
}
)
message = client.messages.create(
model="MODEL_NAME", # replace with a vision-capable model from the provider's docs
max_tokens=1024,
messages=[{"role": "user", "content": blocks}],
)
print(message.content[0].text)Two details matter here. The label comes before each image, so the association between label and page is unambiguous. The question comes after all the images, which the multiple-images chapter recommends for most models. If you use the OpenAI Responses API instead, the same idea applies with input_image blocks and data URLs.
Choosing DPI and keeping size under control
Pick the lowest DPI at which the smallest text you care about is still legible to a human looking at the image. A practical procedure:
- Render one representative page at 100, 150, and 200 DPI.
- Open each and check whether the smallest relevant text (footnotes, table cells) is readable.
- Choose the lowest DPI that passes, and test it on a few more pages.
PNG is lossless and suits text and line art, but a full page can reach several hundred kilobytes, and a page of dense graphics can exceed a megabyte. If you hit request size limits, you have three options:
- Lower the DPI.
- Convert to JPEG at quality 85 to 90 using the downscaling helper from the preprocessing chapter. Text stays readable, but heavy compression produces artifacts around thin strokes.
- Split the document into several requests, then combine the results.
Remember that base64 inflates payload size by about one third, so a 3.5 MB image becomes roughly 4.7 MB in the request body.
Cropping regions
When only a table or a figure matters, render just that area. PyMuPDF accepts a clip rectangle in PDF points, where one point is 1/72 inch.
import fitz # PyMuPDF
def render_region(pdf_path, page_index, rect, dpi=200):
"""Render a rectangle (x0, y0, x1, y1 in points) of one page to PNG bytes."""
with fitz.open(pdf_path) as doc:
clip = fitz.Rect(*rect)
pix = doc[page_index].get_pixmap(dpi=dpi, clip=clip)
return pix.tobytes("png")
# Top half of the first page of a Letter-sized document
table_png = render_region("report.pdf", 0, (0, 0, 612, 396))
print(len(table_png))A cropped region at a high DPI gives the model more pixels on the part you care about, at a lower cost than a full page at the same DPI.
Edge cases
- Rotated pages. Scanned documents are sometimes stored sideways with a rotation flag. PyMuPDF applies the page's rotation when rendering, but a scan whose pixels are physically sideways stays sideways. If answers look garbled, view a rendered page before blaming the model.
- Password-protected files.
fitz.opensucceeds, but pages cannot be read until you authenticate. Checkdoc.needs_passand calldoc.authenticate(password)first. - Very long documents. Rendering all pages at once holds every PNG in memory. Render and send in batches, or stream pages to disk.
- Transparent backgrounds. Some pages have no background fill, and a PNG with alpha can show black behind dark text in some viewers. Rendering with
alpha=False, which is the default forget_pixmap, gives a white background. - Text that is already selectable. If the PDF contains real text, rendering throws that information away and forces the model to read pixels. The next chapter covers when to extract text instead.
Cost and latency
Every page image is billed as image tokens, and a 20-page document sent as 20 images can cost far more than the same text. Provider formulas differ, but they usually scale with pixel count. Before running a large batch, send one page and read the usage fields in the response to measure real token use, then multiply by your page count. Sending more pages also increases latency, so rendering only the pages you need is the most effective saving.
Exercise
A 40-page PDF has a financial summary table on page 12 with footnotes in small print. You want to ask a model questions about that table using rendered images. Which pages and settings would you send, and why? Include the index you pass to the rendering function.
Show answer
Render only page 12, which is index 11 because PyMuPDF indexes pages from zero. Use a DPI high enough for the footnotes to be readable, such as 200, after checking a lower DPI first. If the table occupies only part of the page, render that region with a clip rectangle so more pixels go to the table. Label the image "Page 12:" before the image block and place the question after it. Sending the other 39 pages would add token cost and latency without helping the answer.
Exercise
You render a scanned PDF at 300 DPI and the provider rejects the request for being too large. Name two changes that reduce size, and say what each one risks.
Show answer
Lower the DPI, which risks making small text illegible. Convert the PNGs to JPEG at quality 85 to 90, which shrinks files but can blur thin strokes if the quality is set too low. Splitting the pages across several requests also works, at the cost of combining answers afterwards.