Extract Text from PDF Documents
Vision models on the IONOS CLOUD AI Model Hub accept image input only. To process a PDF document, each page must be rendered as an image before it is sent to the model. This guide shows how to do that using pypdfium2, a lightweight PDF rendering library, together with the OpenAI-compatible API.
About this guide
In this guide, you will learn how to:
Render PDF pages as images using
pypdfium2Extract text from a PDF using LightOnOCR-2-1B, a model optimized for document OCR
Extract and understand content from a PDF using Mistral Small 24B, a multimodal language model
Prerequisites
Before you start, make sure you have:
Python 3.11 or higher installed on your machine
The
IONOS_API_TOKENenvironment variable set with your authentication tokenA PDF file to process
Download the code files to follow with ready-to-use examples:
Download the Python Notebook to explore PDF text extraction with ready-to-use examples.
Download the standalone Python script for a quick implementation.
Step 1: Install dependencies
Step 2: Choose a model
The IONOS CLOUD AI Model Hub offers two model types suitable for PDF text extraction:
Model
Identifier
Best for
LightOnOCR-2-1B
lightonai/LightOnOCR-2-1B
Pure text extraction from scanned documents and complex layouts
Mistral Small 24B
mistralai/Mistral-Small-24B-Instruct
Text extraction combined with document understanding and Q&A
Step 3: Render a PDF page as an image
pypdfium2 renders each PDF page as a PNG image in memory. The scale=2.0 parameter renders at 200 DPI, which balances text sharpness with request payload size.
The function returns a base64-encoded PNG string ready to send directly to the API.
Step 4: Send a page to the API
LightOnOCR-2-1B does not require a prompt — its output behaviour is embedded in the model weights.
Mistral Small 24B accepts a text prompt alongside the image, which lets you control the extraction or ask questions about the page content.
Step 5: Process all pages in a PDF
To extract text from every page, iterate over the page count and collect the results:
What you learned
In this guide, you learned how to:
Render PDF pages as base64-encoded PNG images using
pypdfium2Send page images to LightOnOCR-2-1B or Mistral Small 24B through the OpenAI-compatible API
Process all pages in a document and collect the results
For pure OCR tasks, LightOnOCR-2-1B delivers fast and structured Markdown output. For tasks that combine extraction with document understanding, Mistral Small 24B offers more flexibility through its text prompt.
For more information about OCR capabilities, see the Optical Character Recognition (OCR) guide.
Last updated
Was this helpful?