PDF Page Control
Use pdf_routing on POST /v1/ocr to control how each PDF page is read. Read clean embedded text from the file, OCR a signature page, skip an appendix, or ignore a small logo. The OCR pages use the engine you chose.
How Pages Are Read
Send pdf_routing: {} for the defaults: mode: "auto", needs_ocr: "ocr", pictures: "read", no overrides, and the request's engine for OCR. In auto mode:
- Clean embedded text can answer a page from the file. The router checks that it is readable and visible, has enough words (default 50), and agrees with a quick OCR check. Hidden, covered or unreadable text cannot answer the page. Complex scripts also go to OCR.
- Pictures, annotations (including form fields and signatures), drawings or too little text send the page to your engine. When usable embedded text is also present, the engine's reading is primary and the embedded text is returned alongside it.
needs_ocrcontrols pages whose embedded text is missing, hidden, covered, unreadable or in a complex script. It also applies when the quick OCR check disagrees or cannot finish. It does not suppress OCR triggered by pictures, annotations, drawings or too little text on an otherwise usable text page.
If your chosen engine is itself the quick-check engine and needs_ocr is skip or error, otherwise clean text can be returned without that OCR check (embedded_text_unverified).
Without page_count, every page of a base64 PDF is selected, up to the engine's limit; set it to select only the first pages. A PDF sent by URL is not counted first, so without page_count only its page 1 is selected. Check max_pages (also returned as max_pages_per_request) in GET /v1/engines before sending multiple pages. Most engines, including the LLM engines, accept only one page per request. A larger page_count is refused even if you plan to skip pages.
API Parameters
pdf_routing is a top-level request object alongside engine and input. Its fields are optional. Overrides take precedence over the document defaults.
Swipe the table sideways to read descriptions.
| Parameter | Type | Default | Description |
|---|---|---|---|
| page_count | integer | whole document (base64); 1 (URL) | Select the first N pages, up to the engine's own limit and at most 1000. Without it a base64 PDF is read whole within those limits (402 if your balance cannot cover every page); a URL, or a PDF the router cannot parse in time, is not counted first, so it reads page 1. Over 20 pages runs as a background job (202). |
| pdf_routing.mode | string | auto | auto chooses per page; ocr sends every selected page to your engine; file_text uses only embedded text. file_text rejects pages without usable embedded text with 422. It bypasses the word minimum and quick OCR check, including when used as an override. |
| pdf_routing.needs_ocr | string | ocr | In auto mode: ocr reads pages needing OCR, skip omits them, error rejects the request with 422 listing those pages before any charge. Explicit overrides win. |
| pdf_routing.pictures | string | read | In auto mode: read lets pictures trigger OCR (by default even a small logo); ignore removes that trigger; large triggers OCR when pictures cover at least 10% of the page. Other OCR checks still apply, including annotations and drawings. |
| pdf_routing.ocr_engine | string | request engine | Must resolve to the same engine as the top-level engine. A different engine is not supported yet and returns 400. Usually leave this out. |
| pdf_routing.overrides | array | [] | Objects with pages (string) and action (ocr, file_text or skip). Each selected page can appear only once. |
Override pages are numbered from 1. Use a single page ("4"), an inclusive range ("3-5"), or a comma-separated list ("1,3-5"). Spaces are allowed. Zero, reversed ranges, duplicate pages, overlapping overrides and pages outside the selection are rejected with 400. Overrides do not select additional pages: set page_count to include them.
Examples
These examples use local-doctr, an engine that can OCR multiple rasterized PDF pages. Replace the sample URL with your PDF URL; its path must end in .pdf (a query string is fine). For other links, download the file and send it as base64 with mime_type: "application/pdf". Reuse the same Idempotency-Key and body when retrying a request; it replays without a new charge. Changing pdf_routing with the same key returns 409 idempotency_key_reused. Keep the first response yourself when OCR history is off.
Read a mixed PDF with the defaults
curl -X POST https://api.open-ocr.com/v1/ocr \
-H "Authorization: Bearer sk-ocr-your-api-key" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{
"engine": "local-doctr",
"page_count": 5,
"input": { "type": "url", "url": "https://example.com/mixed.pdf" },
"pdf_routing": {}
}'OCR the signature page, skip an appendix, ignore a small logo
Page 4 always goes to OCR and page 5 is skipped. On other pages, pictures covering less than 10% do not trigger OCR. A small-logo page can use file text if its other checks pass. For a signature drawn into the page image, an explicit OCR override ensures the engine reads it even when the picture is small.
curl -X POST https://api.open-ocr.com/v1/ocr \
-H "Authorization: Bearer sk-ocr-your-api-key" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{
"engine": "local-doctr",
"page_count": 5,
"input": { "type": "url", "url": "https://example.com/contract.pdf" },
"pdf_routing": {
"pictures": "large",
"overrides": [
{ "pages": "4", "action": "ocr" },
{ "pages": "5", "action": "skip" }
]
}
}'Reject a document if any automatic page needs OCR
curl -X POST https://api.open-ocr.com/v1/ocr \
-H "Authorization: Bearer sk-ocr-your-api-key" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{
"engine": "local-doctr",
"page_count": 5,
"input": { "type": "url", "url": "https://example.com/mixed.pdf" },
"pdf_routing": { "needs_ocr": "error" }
}'A scanned page 2 causes 422 with pages need OCR but pdf_routing.needs_ocr is "error": 2. Nothing is charged. Use needs_ocr: "skip" to omit those pages instead. Pages with usable text plus pictures can still be OCR'd in either case.
Per-Page Pricing and Response
- File-text pages use the PDF Text Layer reader's price ($0.0001/page). The response reports that rate as
metadata.text_layer.price_per_page. - OCR pages use your chosen engine's price. A page read both ways is billed at the engine's price, without an extra file-text page charge.
- Skipped pages cost nothing. Policy validation and document precheck errors occur before any charge.
In a JSON response, metadata.text_layer.pages[] reports each analyzed page. page is the original page number. source is text_layer, ocr, text_layer_and_ocr or skipped. reason explains the text analysis; policy_action is file_text, ocr, both or skip; policy_reason explains the policy decision. Pages read both ways also include embedded_text. A completed quick check can add ocr_check. This example shows selected entries from the signature-page request:
{
"metadata": {
"text_layer": {
"pages": [
{ "page": 1, "source": "text_layer", "reason": "embedded_text", "policy_action": "file_text", "policy_reason": "embedded_text" },
{ "page": 4, "source": "ocr", "reason": "has_pictures", "policy_action": "ocr", "policy_reason": "override_ocr" },
{ "page": 5, "source": "skipped", "reason": "embedded_text", "policy_action": "skip", "policy_reason": "override_skip" }
]
}
}
}mode: "ocr" without overrides skips text analysis, so its report is minimal: each page has only page, source: "ocr", policy_action: "ocr" and policy_reason: "mode_ocr", with no reason, embedded_text or ocr_check.
Errors and Current Limits
Invalid fields, enum values, blank engine IDs and conflicting aliases return 400. For example: page 3 appears in more than one override or override page 9 is outside the selected pages. mode: "file_text" on a scanned page returns 422: file_text requested for pages without usable embedded text: 2. Any policy except mode: "ocr" without overrides needs the PDF text layer. If it is unavailable, the router returns 422 before any charge:pdf_routing needs the PDF text layer to plan this document, and it is unavailable for this request (...). To OCR every page without analysis, use pdf_routing: {"mode": "ocr"} without overrides.
The text layer is unavailable with detect_tables: true, top-level document_context or transcription instructions, and engines that return document structure: AWS Textract, Google Document AI, Docling, Mistral OCR, Datalab, Azure Document Intelligence and Azure Form Recognizer. Native-PDF engines in this list are refused earlier with 400. The text layer is also unavailable when the PDF text reader is disabled or unavailable. On a supported engine, use mode: "ocr" without overrides or remove the conflicting setting.
pdf_routing works on POST /v1/ocr, synchronous or mode: "async", including PDFs over 20 pages that run as background jobs, with a PDF and an engine that OCRs rendered pages. A page_count over 1000 returns 400 (pdf_routing supports at most 1000 pages per document; split the document). These combinations return 400 with "not supported yet":
- Engines that read PDFs natively, such as Mistral OCR.
- Non-PDF input, including a URL whose path does not end in
.pdf. settings.page_rangeornative_settings.page_range.- Scale-to-zero open models (serverless background processing).
- An
ocr_engineor legacyfallback_enginedifferent from the request engine. - A request-level
fallbackretry. /v1/ocr/batchitems.
Batch-only engines cannot be called through this synchronous endpoint either. The engine's max_pages limit still applies. The demo key cannot use pdf_routing.
Large PDFs on engines without native PDF support
The background-job and async examples below apply with or without pdf_routing. Without native PDF support, requests for more than 20 pages run as background jobs. Engines that read PDFs natively can process more than 20 pages in a single synchronous request, up to their own page limit.
When the engine does not read PDFs natively and you request more than 20 pages (page_count above 20, or a longer base64 PDF sent without page_count), the router dispatches a background job without you asking for async. Without page_count, a balance that does not cover every page is refused with 402 before anything is read. With an explicit page_count the balance does not cover, the count is first lowered to what it covers; when that is 20 pages or fewer, no job starts: the request runs synchronously, with the result in the response and no webhook, or, if you sent mode: "async", as an ordinary async request polled at /v1/ocr/{request_id}. Otherwise the POST returns 202 with status: "processing", a warning of the form job_id: job_..., and a poll_url of /v1/ocr/jobs/{job_id}/status, not /v1/ocr/{request_id}. That status endpoint reports progress only; once it shows the job is done, fetch the text from GET /v1/ocr/jobs/{job_id}/result. While the job is still running, /result answers HTTP 202 with {"error":{"code":"processing",...}}, not a result with a status field.
# Progress (job_id, status, total_pages, pages_completed, current_page_type,
# estimated_seconds_remaining, progress_pct)
curl https://api.open-ocr.com/v1/ocr/jobs/job_abc123/status \
-H "Authorization: Bearer sk-ocr-your-api-key"
# Result (job_id, request_id, status, engine, total_pages, extracted_text, error,
# plus pages / pages_total / warnings). While the job runs it answers HTTP 202 with
# {"error":{"code":"processing","message":"Job is still processing. ..."}}.
curl https://api.open-ocr.com/v1/ocr/jobs/job_abc123/result \
-H "Authorization: Bearer sk-ocr-your-api-key"Legacy Scanned-page Settings
scanned_handling and fallback_engine are deprecated top-level aliases. Without pdf_routing, they are validated but have no effect on page processing and produce no response warning. They do not skip pages, reject scanned pages or call a backup engine.
With pdf_routing present (even an empty object), scanned_handling maps fallback to needs_ocr: "ocr", skip to needs_ocr: "skip", and error to needs_ocr: "error". fallback_engine aliases pdf_routing.ocr_engine, so it must name the request engine. Conflicting old and new values return 400. Legacy scanned_handling: "fallback" requires fallback_engine. Without that field it returns 422, with or without pdf_routing.
pdf_text_layer: false in options, settings or native_settings makes an omitted pdf_routing.mode behave as ocr. An explicit auto or file_text conflicts and returns 400. The separate request-level fallback retries eligible failed calls on another engine; it cannot be combined with pdf_routing.
Async Mode for Large Documents
For long PDFs, send mode: "async" (a base64 PDF is read whole without page_count; send page_count with a URL, which is not counted first, or to read only the first pages). The API returns 202 Accepted immediately with a request_id and a poll_url. Ordinary explicit async requests, including the example below, require OCR history on your account. With history off they return 400 history_disabled; use synchronous mode and save the response yourself. Automatically dispatched large-PDF jobs have a separate short-lived result path when history is off.
- Submit the PDF with
mode: "async"(andpage_countfor a URL). - Poll
GET {poll_url}(that is/v1/ocr/{request_id}) untilstatusis no longerqueuedorprocessing. Polling returns succeeded, partial, failed or rejected as terminal statuses (refunded and timeout appear only in the POST response; GET reports them as failed). For a partial result onlyextracted_text_previewis stored, so the full partial text is not available from polling. Stop on any terminal status. - Read
statusandcost_debitedfrom the completed status response. On success, read any retainedextracted_textand available page accounting.
# 1. Submit the PDF asynchronously, for the first 60 pages
curl -X POST https://api.open-ocr.com/v1/ocr \
-H "Authorization: Bearer sk-ocr-your-api-key" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{
"engine": "mistral-mistral-ocr-4-1",
"mode": "async",
"page_count": 60,
"input": { "type": "url", "url": "https://example.com/annual-report.pdf" }
}'
# 202 Accepted
# { "request_id": "req_abc123", "status": "processing", "poll_url": "/v1/ocr/req_abc123" }
# 2. Poll until status is neither "queued" nor "processing"
# (terminal: succeeded, partial, failed, rejected; for partial read extracted_text_preview)
curl https://api.open-ocr.com/v1/ocr/req_abc123 \
-H "Authorization: Bearer sk-ocr-your-api-key"Python — Polling Example
import time
import base64
import uuid
import requests
API_KEY = "sk-ocr-your-api-key"
BASE_URL = "https://api.open-ocr.com"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Idempotency-Key": str(uuid.uuid4()), # required on POST /v1/ocr; new UUID per logical request
}
with open("large-document.pdf", "rb") as f:
pdf_b64 = base64.b64encode(f.read()).decode()
# Submit asynchronously. Without page_count every page is read.
resp = requests.post(f"{BASE_URL}/v1/ocr", headers=headers, json={
"engine": "mistral-mistral-ocr-4-1",
"mode": "async",
"input": {"type": "base64", "data_base64": pdf_b64, "mime_type": "application/pdf"},
})
resp.raise_for_status()
poll_url = resp.json()["poll_url"] # e.g. "/v1/ocr/req_abc123"
while True:
poll = requests.get(f"{BASE_URL}{poll_url}", headers=headers)
poll.raise_for_status() # an HTTP error body has no "status"; do not keep polling on it
result = poll.json()
# queued and processing are the only non-terminal statuses. GET returns succeeded, partial,
# failed or rejected as terminal.
if result["status"] not in ("queued", "processing"):
break
time.sleep(3)
if result["status"] == "partial":
# Only extracted_text_preview is stored for a partial result (extracted_text is null).
print("WARNING: partial result:", result.get("warning"))
text = result["extracted_text_preview"]
elif result["status"] != "succeeded":
raise RuntimeError(f"OCR ended as {result['status']}: {result.get('provider_error')}")
else:
text = result["extracted_text"]
print(text)TypeScript — Polling Example
const API_KEY = "sk-ocr-your-api-key";
const BASE_URL = "https://api.open-ocr.com";
async function ocrPdf(pdfBase64: string): Promise<string> {
const headers = {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": crypto.randomUUID(), // required on POST /v1/ocr
};
// Submit asynchronously. Without page_count every page is read.
const submitRes = await fetch(`${BASE_URL}/v1/ocr`, {
method: "POST",
headers,
body: JSON.stringify({
engine: "mistral-mistral-ocr-4-1",
mode: "async",
input: { type: "base64", data_base64: pdfBase64, mime_type: "application/pdf" },
}),
});
// Async needs OCR history enabled; otherwise this is a 400 history_disabled with no poll_url.
if (!submitRes.ok) throw new Error(`submit failed: ${submitRes.status} ${await submitRes.text()}`);
const { poll_url } = await submitRes.json();
while (true) {
await new Promise((r) => setTimeout(r, 3000));
const res = await fetch(`${BASE_URL}${poll_url}`, { headers });
if (!res.ok) throw new Error(`poll failed: ${res.status} ${await res.text()}`);
const result = await res.json();
// queued and processing are the only non-terminal statuses.
if (result.status === "queued" || result.status === "processing") continue;
if (result.status === "partial") {
// Only extracted_text_preview is stored for a partial result (extracted_text is null).
console.warn("partial result:", result.warning);
return result.extracted_text_preview as string;
}
if (result.status !== "succeeded") {
throw new Error(`OCR ended as ${result.status}: ${result.provider_error ?? ""}`);
}
return result.extracted_text as string;
}
}Credit Exhaustion Mid-Document
Before processing a multi-page PDF, the router checks your balance against the estimated cost. If your balance is insufficient:
- Balance = 0 — request is rejected immediately with
402 Payment Required. - No
page_countand balance < full cost — the request is refused with402 insufficient_balancebefore anything is read or charged. The message gives the page count, the cost and how many pages your balance covers. - Explicit
page_countand balance < full cost — the response includesaffordable_pagesshowing how many pages your balance covers. Processing continues up to that limit and returns results for the affordable pages, still withstatus: "succeeded"andstop_reason: "credit_exhaustion".
{
"request_id": "req_abc123",
"status": "succeeded",
"extracted_text": "Page 1 content\n\n---\n\nPage 2 content\n\n---\n\nPage 3 content",
"stopped_at_page": 3,
"stop_reason": "credit_exhaustion",
"remaining_pages": 17,
"affordable_pages": 3
}FAQ
What about PDFs with digital signatures?
The classifier labels a page digital or scanned based on its selectable text count; it does not detect or verify signatures. A signature image on a digital page can be missed by text extraction. Choose an engine that reads the page image when that visual content matters; OpenOCR does not verify cryptographic signatures.
Are password-protected PDFs supported?
Submit an unlocked copy. A protected PDF may fail in classification, preprocessing or the chosen engine; a fixed HTTP status is not guaranteed for every path.
How long are async job results stored?
With OCR history enabled, completed background jobs are also stored in the database; the one-hour in-memory cache is not the lifetime of the saved result. With history off, an automatically dispatched PDF job has a one-use in-memory result window of up to one minute after completion. Fetch it promptly and save it yourself; after that window or a successful retrieval, the job result may return 404. If a service update interrupts that window, the finished text is kept encrypted for up to one hour so you can still collect it once; it is deleted when collected or when the hour ends.
Can I force async mode for small PDFs?
Yes. Set mode: "async" even for a small PDF when OCR history is enabled. On an image-only engine, a PDF requested for more than 20 pages also starts a background job automatically; that job uses the separate job status and result URLs.
What if a page fails in an automatically dispatched PDF job?
In a multi-page job on an image-only engine, a failed page is listed in the job warnings and appears as a numbered [Page N could not be read] placeholder if other pages produced text. A job with no readable text fails instead of reporting a successful OCR result. Ordinary explicit async requests use the whole-call result and do not have these per-page placeholders.