# Pdf Json Extractor (`p6t_p10n/pdf-json-extractor`) Actor

Convert any PDF into structured JSON using AI and OCR (Tesseract or Google Vision). Supports custom schemas, validation, and auto-repair. Ideal for invoices, contracts, receipts, and automation workflows. Fast, accurate, and easy to integrate.

- **URL**: https://apify.com/p6t\_p10n/pdf-json-extractor.md
- **Developed by:** [Peerapat Pongnipakorn](https://apify.com/p6t_p10n) (community)
- **Categories:** AI, Automation, Developer tools
- **Stats:** 2 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $50.00 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## PDF → Structured JSON Extractor (Apify Actor)

This Apify Actor extracts structured JSON from PDF files using PDF parsing + optional OCR + LLM-based schema extraction.

### Features

- Accepts a `pdfUrl` (HTTP) or `pdfBase64` (string) as input
- Extracts raw text using `pdf-parse` and optionally OCR (stub)
- Sends the text and a user-provided `schema` to an LLM to return strict JSON
- Pushes extraction result to Dataset

### Quick start

1. Update `main.js`'s `callLLM` function to call your chosen LLM provider (OpenAI, Anthropic, Google)
2. (Optional) Implement `runOCR` using Tesseract or a cloud OCR API
3. `apify push` to your Apify account and run the actor with `input.json`

### Example input.json

```json
{
  "pdfUrl": "https://example.com/invoice123.pdf",
  "schema": {
    "invoice_number": "string",
    "invoice_date": "date",
    "total_amount": "number",
    "items": [{ "name": "string", "qty": "number", "price": "number" }]
  },
  "aiModel": "gpt-4o-mini",
  "ocr": false,
  "returnFormat": "json"
}
```

### Notes

- The starter `callLLM` function is a stub for testing and must be replaced with an actual LLM API call before production use.
- Consider rate limits and cost of LLM calls. Offer batching or model selection in your product.

### Suggested pricing

- Free: 20 PDFs / month
- Starter: $19 / month (200 PDFs)
- Pro: $49 / month (1000 PDFs)
- Business: $149 / month (10k PDFs)

### Validation & LLM retry behavior

This Actor now validates the extracted JSON using `ajv` when you provide a JSON Schema as the `schema` input. If the JSON does not validate, the Actor will automatically attempt to repair it by sending a targeted prompt to the LLM (up to 2 repair attempts).

LLM calls use `p-retry` with exponential backoff for transient failures (retries on 5xx and rate-limit responses). You can control retry counts and model via the input parameters.

### OCR Options (Tesseract or Google Vision)

This Actor supports optional OCR when `ocr` is enabled in the input. You can select the OCR engine via the input `ocrOptions.engine` field.

#### `ocrOptions` example

```json
"ocr": true,
"ocrOptions": { "engine": "tesseract" }
```

or for Google Vision:

```json
"ocr": true,
"ocrOptions": { "engine": "google" }
```

#### Tesseract (offline)

- Uses `tesseract.js` (Node). This allows OCR without external APIs but adds a larger dependency.
- No env vars needed. Install dependencies and run the Actor as usual.

#### Google Vision (cloud OCR)

- Uses Google Vision `DOCUMENT_TEXT_DETECTION` endpoint. Requires `GOOGLE_API_KEY` env var with an API key that has Vision API enabled.
- Set the key in environment before running:

```bash
export GOOGLE_API_KEY="YOUR_GOOGLE_VISION_API_KEY"
```

#### Behavior notes

- The Actor will attempt `pdf-parse` extraction first. If `ocr` is true and extracted text is short or empty, the configured OCR engine will be invoked.
- OCR can be slower and more expensive (Google Vision costs), so use it only for scanned PDFs.

# Actor input Schema

## `pdfUrl` (type: `string`):

URL of the PDF to download and extract.

## `pdfBase64` (type: `string`):

Base64 encoded content of the PDF (alternative to URL).

## `schema` (type: `object`):

JSON schema describing the data you want to extract.

## `aiModel` (type: `string`):

OpenAI model to use.

## `ocr` (type: `boolean`):

Use OCR if text extraction fails or text is too short.

## `returnFormat` (type: `string`):

Format of the output.

## Actor input object example

```json
{
  "schema": {
    "invoice_number": "string",
    "total_amount": "number"
  },
  "aiModel": "gpt-4o-mini",
  "ocr": false,
  "returnFormat": "json"
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "schema": {
        "invoice_number": "string",
        "total_amount": "number"
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("p6t_p10n/pdf-json-extractor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "schema": {
        "invoice_number": "string",
        "total_amount": "number",
    } }

# Run the Actor and wait for it to finish
run = client.actor("p6t_p10n/pdf-json-extractor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "schema": {
    "invoice_number": "string",
    "total_amount": "number"
  }
}' |
apify call p6t_p10n/pdf-json-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,p6t_p10n/pdf-json-extractor"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/bdIHkXUdHbNmLELhU/builds/rHZ7nIWLhuDJM6gAr/openapi.json
