How to Use OCR to Extract Text from PDF Images with Python
Extract Text from Scanned PDFs with OCR and Python
A PDF can display readable words without containing machine-readable text. Scanned pages often store each page as an image, so a normal text-extraction request may return little or no useful content. The pdfRest OCR PDF API Tool recognizes characters in the page images and adds a searchable text layer to the PDF. The Extract Text API Tool can then return that recognized text to your Python application. Using both tools through the same API gives you a direct path from scanned pages to usable document data without installing and maintaining a separate OCR engine and PDF text parser.
This tutorial combines the two operations in one resource-based workflow:
For example, a records-intake application may receive scanned enrollment forms that cannot be searched or indexed because each page contains only an image. The application can use OCR PDF to recognize the characters, pass the resulting resource ID to Extract Text, and store the returned text so staff can locate forms by name or account number without manually retyping their contents.
- Upload the scanned PDF to
/pdf-with-ocr-text. - Read the OCR-processed PDF's
outputIdfrom the response. - Send that ID to
/extracted-text. - Read the extracted content from the second response.
Passing the resource ID between calls avoids downloading and re-uploading the intermediate OCR PDF. This resource-based chaining is built into pdfRest, so the same pattern can connect OCR and extraction to other document operations without moving an intermediate file through your application after every step.
Python OCR and Text Extraction Example
The sample requires Python, the requests and requests-toolbelt packages, a pdfRest API key, and a scanned or image-based PDF. Replace the API-key and file-path placeholders before running it.
from requests_toolbelt import MultipartEncoder
import requests
# In this sample, we will show how to convert a scanned document into a PDF with
# searchable and extractable text using Optical Character Recognition (OCR), and then
# extract that text from the newly created document.
#
# First, we will upload a scanned PDF to the /pdf-with-ocr-text route and capture the
# output ID. Then, we will send the output ID to the /extracted-text route, which will
# return the newly added text.
# By default, we use the US-based API service. This is the primary endpoint for global use.
api_url = "https://api.pdfrest.com"
# For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
# For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
#api_url = "https://eu-api.pdfrest.com"
api_key = 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here
ocr_endpoint_url = api_url+'/pdf-with-ocr-text'
mp_encoder_pdf = MultipartEncoder(
fields={
'file': ('file_name.pdf', open('/path/to/file.pdf', 'rb'), 'application/pdf'),
'output': 'example_pdf-with-ocr-text_out',
}
)
image_headers = {
'Accept': 'application/json',
'Content-Type': mp_encoder_pdf.content_type,
'Api-Key': api_key
}
print("Sending POST request to OCR endpoint...")
response = requests.post(ocr_endpoint_url, data=mp_encoder_pdf, headers=image_headers)
print("Response status code: " + str(response.status_code))
if response.ok:
response_json = response.json()
ocr_pdf_id = response_json["outputId"]
print("Got the output ID: " + ocr_pdf_id)
extract_endpoint_url = api_url+'/extracted-text'
mp_encoder_extract_text = MultipartEncoder(
fields={
'id': ocr_pdf_id
}
)
extract_text_headers = {
'Accept': 'application/json',
'Content-Type': mp_encoder_extract_text.content_type,
'Api-Key': api_key
}
print("Sending POST request to extract text endpoint...")
extract_response = requests.post(extract_endpoint_url, data=mp_encoder_extract_text, headers=extract_text_headers)
print("Response status code: " + str(extract_response.status_code))
if extract_response.ok:
extract_json = extract_response.json()
print(extract_json["fullText"])
else:
print(extract_response.text)
else:
print(response.text)
Source: pdfRest OCR and Extract Text Python sample on GitHub
If the scanned PDF already exists on the pdfRest processing service, both steps can use JSON payloads with resource IDs instead of uploading the file as multipart data. See the OCR PDF JSON-payload sample and the Extract Text JSON-payload sample.
How the Two API Calls Work Together
The first multipart request uploads the source file to /pdf-with-ocr-text. A successful response contains an outputId for the new PDF with its recognized text layer. The script stores that value as ocr_pdf_id and supplies it as the id field in the second multipart request.
The /extracted-text endpoint works from that server-side resource and returns the recognized content in JSON. The sample prints fullText, which is useful when the application needs a document-level string for search indexing, data analysis, or another text-processing step.
The Extract Text tool also supports more detailed output. Depending on the application, you can request full text by page or document, preserve line breaks, include coordinates for each word, and include font or color information. This lets one API support simple full-text indexing as well as layout-aware extraction without forcing every application into the same response shape. Coordinate and style data are useful when layout matters; plain full text is usually simpler for search, classification, or language-processing workflows.
Choose OCR Languages and Inputs Carefully
OCR defaults to English when no language is supplied. For documents in other languages, use the optional languages parameter and follow the current OCR PDF API reference for supported ISO 639-2 Alpha-3 language codes. Limiting recognition to the languages actually present can improve the balance between accuracy and processing time, especially for multilingual or CJK documents.
OCR is most valuable for scanned and image-only content. Born-digital PDFs may already contain extractable text, while mixed PDFs can contain both existing text and page images. Query PDF can identify image-only files so the application routes each document through the appropriate extraction path automatically.
Build OCR into a Reliable Extraction Workflow
OCR gives image-based documents a searchable text layer that the application can route directly into Extract Text, search, classification, or data-entry workflows. Recognition quality reflects the characteristics of the scanned page, including resolution, rotation, contrast, language, font, and page condition.
For workflows that act on names, amounts, identifiers, or other decisive values, design field-level business rules around the extracted result. The API response provides the processing status and expected output fields; application logic can use those fields to route a clean result forward or flag an exception for the process that owns the underlying data. This turns OCR from a manual recovery step into a useful part of a repeatable document-intake workflow.