Document Processing API — PDF, OCR & Validated JSON avatar

Document Processing API — PDF, OCR & Validated JSON

Pricing

from $20.00 / 1,000 document results

Go to Apify Store
Document Processing API — PDF, OCR & Validated JSON

Document Processing API — PDF, OCR & Validated JSON

Extract schema-validated JSON from PDFs, scans, images, DOCX, XLSX, emails, and text. Includes OCR, field evidence, custom rules, and workflow routing—no model API key required.

Pricing

from $20.00 / 1,000 document results

Rating

0.0

(0)

Developer

Scalogik LLC

Scalogik LLC

Maintained by Community

Actor stats

0

Bookmarked

2

Total users

1

Monthly active users

a day ago

Last modified

Categories

Share

Document Processing API — PDF, OCR and validated JSON

Document Processing API — PDF, OCR & Validated JSON

Turn PDFs, scans, images, DOCX files, spreadsheets, emails, and text documents into schema-validated JSON. This AI document processing API extracts exactly the fields in your JSON Schema, returns field-level evidence, applies deterministic validation rules, and routes every document to accepted, review, or rejected.

No separate model-provider API key is required. Upload a file or send document URLs, define the JSON you need, and receive workflow-ready results through Apify Console, REST API, Python, JavaScript, schedules, webhooks, or MCP. The Actor uses Apify OpenRouter with the token of the account that starts the run, so managed model-token usage is billed separately by Apify.

Built for reliable automation: constrained JSON output, local schema validation, evidence coverage, safe repair, transparent errors, and no successful-result charge when processing fails.

What this document processing API does

Most OCR APIs return text. Most PDF-to-JSON tools return a fixed structure. This Actor lets you define a custom Draft 2020-12 JSON Schema and combines extraction with validation and routing in one run.

CapabilityWhat you receive
Custom document data extractionOnly the fields and types declared in your JSON Schema
PDF and OCR processingDigital PDF text extraction plus visual processing for scans and images
Validated JSON outputA local schema-validation result and exact violation paths
Evidence-backed extractionSource quote, page or section, confidence, and verification state per field
Custom workflow rulesDeclarative checks such as required values, regex, equality, range, and presets
Decision routingaccepted, review, or rejected for each document
Batch safetyPer-document errors, fail-fast control, document limits, and spending-limit stop
Managed AIGemini extraction through Apify OpenRouter; no separate provider key, with model-token usage billed by Apify to the run starter

Supported document formats

The API accepts PDF, PNG, JPEG, WEBP, DOCX, XLSX, EML, CSV, JSON, HTML, Markdown, and plain text. Digital documents are parsed locally when possible. Scanned PDFs and direct image uploads are normalized into bounded JPEG inputs before managed visual extraction, preventing oversized base64 requests.

Format groupExamplesProcessing path
PDFDigital and scanned PDFLocal text extraction or bounded page rendering
ImagesPNG, JPEG, WEBPMultimodal visual extraction
OfficeDOCX, XLSXLocal text and cell extraction
EmailEMLHeaders and plain/HTML body extraction
Structured textCSV, JSON, HTML, Markdown, TXTLocal normalization before extraction

Common use cases

WorkflowExample JSON fields
Invoice extraction APIinvoice number, dates, supplier, VAT ID, currency, line items, totals
Receipt OCR APImerchant, transaction date, tax, total, payment method
Purchase-order processingPO number, buyer, supplier, SKUs, quantities, delivery date
Certificate-of-Analysis parserbatch, analyte, method, specification, result, unit, pass/fail
Safety Data Sheet extractionproduct, CAS numbers, hazards, PPE, transport class
Freight document automationBOL number, shipper, consignee, freight class, weight, accessorials
Application and onboarding formsapplicant fields, missing evidence, validation status
Email attachment workflowsnormalized message fields and document-derived business data

Quick start: extract an invoice to JSON

Use the prefilled example in Apify Console for a safe first run. For your own document, provide one file and a schema:

{
"document": "https://example.com/invoice.pdf",
"outputSchema": {
"type": "object",
"properties": {
"invoiceNumber": { "type": ["string", "null"] },
"invoiceDate": { "type": ["string", "null"] },
"supplierName": { "type": ["string", "null"] },
"currency": { "type": ["string", "null"] },
"total": { "type": ["number", "null"] }
},
"required": ["invoiceNumber", "invoiceDate", "supplierName", "currency", "total"],
"additionalProperties": false
},
"validationRules": [
{
"field": "currency",
"operator": "matchesPreset",
"preset": "currencyCode",
"severity": "error"
},
{
"field": "total",
"operator": "gte",
"value": 0,
"severity": "error"
}
],
"routePolicy": "standard",
"includeEvidence": true
}

The Actor returns one dataset row per document:

{
"documentId": "330e4f07fb30a813",
"filename": "invoice.pdf",
"status": "success",
"route": "accepted",
"schemaValid": true,
"data": {
"invoiceNumber": "INV-2026-0042",
"invoiceDate": "2026-09-02",
"supplierName": "Northwind Components OÜ",
"currency": "EUR",
"total": 186.0
},
"evidence": {
"total": [
{
"value": "186.00",
"quote": "Total: 186.00 EUR",
"page": 1,
"confidence": 1.0,
"verified": true
}
]
},
"evidenceCoverage": 1.0,
"violations": [],
"warnings": [],
"processing": {
"model": "google/gemini-2.5-flash",
"attempts": 1,
"durationMs": 5178,
"modelCostUsd": 0.0024
},
"error": null
}

modelCostUsd is the diagnostic managed-model cost observed during processing. It corresponds to the separate Apify OpenRouter model-token usage billed to the account that starts the run; it is not an additional Scalogik Actor event charge.

Define your validated JSON output

outputSchema uses a safe subset of JSON Schema Draft 2020-12.1 The root must be an object. Supported field types are object, array, string, number, integer, boolean, and null. Nested objects and arrays are supported within launch limits.

Use nullable required fields when a document may omit information:

{
"type": "object",
"properties": {
"policyNumber": { "type": ["string", "null"] },
"insuredValue": { "type": ["number", "null"] }
},
"required": ["policyNumber", "insuredValue"],
"additionalProperties": false
}

This structure forces the model to return predictable keys while preserving an explicit null when the source does not contain a value.

Add deterministic validation rules

AI extracts the fields; deterministic code evaluates your business checks. Rules use dotted field paths such as supplier.vatId or lineItems.0.sku.

OperatorPurposeExample
required / existsField must contain a valueInvoice number is present
equals / notEqualsExact value comparisonCurrency equals EUR
containsString or array membershipDescription contains a term
regexFull-string pattern validation with a short safety timeoutInternal reference format
gt, gte, lt, lteNumeric comparisonTotal is greater than zero
inValue belongs to an allowlistDocument type is permitted
matchesPresetCommon formatsEmail, ISO date, currency code, VAT ID

Rules have error or warning severity. The standard route policy sends schema or rule errors to rejected, warnings or evidence coverage below 60% to review, and clean results to accepted. The conservative policy reviews warnings or coverage below 90%; strict also rejects warnings or incomplete evidence; review_all sends every schema-valid, rule-clean extraction to review.

Evidence and review queues

Each populated scalar field can include a verbatim source quote and page or section reference. Evidence from locally extracted text is checked against the source and marked verified: true or false. Visual-only evidence is marked verified: null because there is no independent text layer against which to compare it.

evidenceCoverage reports the share of populated scalar fields with evidence. This makes it possible to route incomplete extractions to review without treating model confidence as proof.

API integration

Apify generates REST, Python, JavaScript, CLI, webhook, schedule, and MCP integration options for every Actor.2

REST API

curl -X POST \
"https://api.apify.com/v2/acts/scalogik~document-processing-api-pdf-ocr-validated-json/run-sync-get-dataset-items" \
-H "Authorization: Bearer $APIFY_TOKEN" \
-H "Content-Type: application/json" \
-d @input.json

Python

from apify_client import ApifyClient
client = ApifyClient("<APIFY_TOKEN>")
run = client.actor("scalogik/document-processing-api-pdf-ocr-validated-json").call(
run_input={
"document": "https://example.com/invoice.pdf",
"outputSchema": {
"type": "object",
"properties": {
"invoiceNumber": {"type": ["string", "null"]},
"total": {"type": ["number", "null"]},
},
"required": ["invoiceNumber", "total"],
"additionalProperties": False,
},
}
)
items = list(client.dataset(run["defaultDatasetId"]).iterate_items())

JavaScript

import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: '<APIFY_TOKEN>' });
const run = await client.actor('scalogik/document-processing-api-pdf-ocr-validated-json').call({
document: 'https://example.com/invoice.pdf',
outputSchema: {
type: 'object',
properties: {
invoiceNumber: { type: ['string', 'null'] },
total: { type: ['number', 'null'] },
},
required: ['invoiceNumber', 'total'],
additionalProperties: false,
},
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();

MCP and AI agents

After publication, add the Actor through Apify’s hosted MCP server. OAuth-capable clients can connect without placing an API token in the MCP configuration.3

https://mcp.apify.com/?tools=fetch-actor-details,scalogik/document-processing-api-pdf-ocr-validated-json

Input reference

InputTypeRequiredDescription
documentFile/URL stringOne sourceSingle-click upload or HTTPS file URL
documentUrlsURL arrayOne sourceBatch of public HTTPS documents
inlineDocumentsObject arrayOne sourceAPI-supplied text with filename and MIME type
outputSchemaJSON objectYesRequired validated output structure
extractionInstructionsStringNoField interpretation or workflow context
validationRulesObject arrayNoUp to five deterministic checks
routePolicyEnumNostandard, strict, or review_all
pdfModeEnumNoauto, digital, or scanned
includeEvidenceBooleanNoReturn source evidence; default true
includeRawTextBooleanNoReturn bounded source text; default false
failFastBooleanNoStop after the first processing error
maxDocumentsIntegerNoRun limit from 1 to 20

You may combine an uploaded document, documentUrls, and inlineDocuments in one run, up to maxDocuments. Results retain a stable one-row-per-source order.

Output reference

FieldMeaning
statussuccess, partial, or error
routeaccepted, review, or rejected
schemaValidWhether data satisfies the requested schema
dataExtracted custom JSON object
evidenceField-indexed quotes, location, confidence, and verification
evidenceCoverageEvidence coverage from 0 to 1
violationsSchema and deterministic-rule failures
warningsNon-fatal extraction, evidence, or format warnings
documentMIME type, size, page count, and SHA-256 hash
processingModel, parser path, attempts, duration, tokens, and model cost
errorStable safe error code, message, and retryability

Pricing

The Scalogik Actor price is $0.02 per successful or partial document result, plus $0.00005 per Actor start. Error results do not receive the document-processed charge. The Actor’s own platform usage is included in this event price. The managed extraction call uses apify/openrouter with the account token for the user who starts the run; Apify bills that account separately for actual model-token usage. Customers need no separate OpenAI, Gemini, or OpenRouter provider key, but should allow for this additional Apify usage charge.

Processed documentsApproximate event price
1$0.02005
100$2.00005
1,000$20.00005

These estimates exclude any optional costs created outside this Actor, such as storing a source file on another service.

Security and privacy

Documents are processed in memory for the run and are not copied into Actor storage. Raw text is excluded from output by default. Stored source URLs omit user information, query strings, and fragments. The downloader rejects non-HTTPS URLs, URL credentials, loopback and private-network destinations, blocked DNS resolutions, unsafe redirects, oversized files, and unsupported content types.

The managed request denies provider data collection where supported. Nevertheless, this service sends document content to a managed model provider for extraction. Do not process documents unless you have the necessary rights, notices, agreements, and retention policy.

Limits and honest expectations

LimitLaunch value
Documents per run20
File size20 MiB
PDF pages50 total
Rendered scanned-PDF pages10
JSON Schema properties150
Spreadsheet cells50,000
Validation rules5
Model repair passes1

No document AI system is perfect. Poor scans, handwriting, complex nested tables, password-protected files, malformed documents, and ambiguous values can produce errors or review results. Use route, violations, and evidence rather than assuming every extracted value is correct.

Quality verification

The private release passed 151 automated tests with 87.99% branch-aware coverage. A controlled Apify Cloud benchmark extracted 70/70 expected fields across digital PDF, scanned PDF, PNG, DOCX, XLSX, EML, and text fixtures. All seven latest format results were schema-valid, had full evidence coverage, and routed to accepted.

The benchmark is deliberately disclosed as a controlled fixture test; it does not predict accuracy on every real-world document. See the repository QA report for method, costs, runs, and limitations.

FAQ

What is the difference between this API and a basic OCR API?

OCR converts pixels into text. This Actor converts documents into a caller-defined JSON structure, validates the output, attaches evidence, applies rules, and assigns a workflow route.

Can I use it as a PDF-to-JSON API?

Yes. Supply a PDF URL or upload and define the JSON Schema. Digital PDFs use local text extraction; scanned PDFs use bounded page-image processing.

Can it extract invoices and receipts?

Yes. Invoice and receipt fields are a common schema, but the Actor is not limited to a fixed financial-document template.

Do customers need an OpenAI, Gemini, or OpenRouter key?

No separate provider key is needed. The Actor uses Apify OpenRouter with the Apify token of the account that starts the run. Apify bills that account separately for actual model-token usage in addition to the Scalogik Actor event price.

Is the returned JSON guaranteed to match my schema?

The Actor validates the result locally. A valid result has schemaValid: true; a failed schema remains visible with violations and is routed according to policy. The API does not silently describe invalid JSON as valid.

Are failed documents charged?

The custom document-processed event is applied only to successful and partial result rows. Error rows are returned without that Scalogik event charge. Any managed-model token use already consumed before an error may still be charged by Apify OpenRouter.

Can I batch documents?

Yes. Provide up to 20 document URLs or inline documents in one run. Each input produces an independent result row.

References