Sub topic 3
Rendering PDF Pages as Images
Assume you know basic Python, JSON, and how to call an LLM API. This chapter focuses on choosing a document representation and checking visual extraction results.
Render PDF pages
When native PDF input is unavailable, render each page to an image. PyMuPDF can produce PNG bytes without creating temporary files:
import fitz # pip install pymupdf
def render_pages(pdf_path, dpi=150):
"""Return PDF pages as PNG byte strings."""
pages = []
with fitz.open(pdf_path) as document:
for page in document:
pixmap = page.get_pixmap(dpi=dpi, alpha=False)
pages.append(pixmap.tobytes("png"))
return pages
pages = render_pages("report.pdf")
print(f"Rendered {len(pages)} pages")Higher DPI improves small-text recognition but increases upload size, token usage, and latency. Start around 150 DPI and raise it only when evaluation shows missed details.
Choose the input form
Use native PDF input when the provider supports it and the document contains tables, diagrams, or mixed layout. Use page images when visual layout matters or native PDF handling is unavailable. Use text extraction for long, text-heavy documents where formatting is unimportant and cost matters most.
Some providers offer file uploads. Upload a document once, retain the returned file identifier, and reference that identifier in later requests. Check retention, expiration, access control, and deletion behavior in the provider documentation. Do not assume an uploaded file is private forever.
Extract and validate data
Ask for a strict structure, such as JSON fields for invoice number, date, and total. Validate the response with a schema and compare important values against the source. For tables, preserve page numbers and row labels so a reviewer can locate each value.
Failure modes and privacy
Common failures include unreadable small text, rotated pages, low contrast, clipped scans, unsupported media types, oversized requests, expired file IDs, and context-limit errors. Log request metadata and provider error codes, but never log document contents or base64 payloads.
Redact personal data when possible. Encrypt files in transit and at rest, restrict file access, use short retention periods, and delete temporary renders after processing.
Test the pipeline
Create a small test set containing clean pages, scans, tables, rotation, small text, and intentionally difficult documents. Measure field accuracy, page-selection accuracy, latency, token usage, and API error rates. Re-test whenever you change DPI, model, prompt, or preprocessing.
Exercise
A PDF contains a chart and a paragraph, but the provider does not accept PDFs. What should you do?
Show answer
Render the relevant page at a suitable DPI, send it as an image with a focused prompt, and validate the extracted claims against the chart.