# PDF Text & OCR Extractor — Scanned PDF to Text API (`eliai/pdf-text-extractor`) Actor

Extract the text from a PDF file. Born-digital or scanned PDFs by URL; OCR runs only when a PDF lacks a text layer. Bulk up to 50 files for RAG and document QA. $0.003 per parsed PDF today; failed URLs free.

- **URL**: https://apify.com/eliai/pdf-text-extractor.md
- **Developed by:** [Broke to Built](https://apify.com/eliai) (community)
- **Categories:** AI, Developer tools, Automation
- **Stats:** 12 total users, 12 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.40 / 1,000 processed pdfs

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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 Text & OCR Extractor — scanned or born-digital PDF to JSON

**Give it a PDF URL, get back the full text plus the document's metadata as JSON.** It reads
both born-digital documents and scanned, image-only pages through automatic OCR. Built for AI
agents, RAG pipelines and document-QA flows: OCR never runs on a usable text layer, there is no
start fee, and failed documents are never charged.

### What you get

- **Full text** extracted from the PDF, ready to embed, index, or summarize.
- **Page count** (`pages`), **character count** (`characters`), and the **PDF format version**.
- **Document metadata** (`info`): title, author, subject, keywords, creator, producer —
  plus creation/modification dates both raw and **normalized to ISO 8601** (`createdAt`,
  `modifiedAt`), so your pipeline gets real timestamps, not `D:20231005120000+02'00'`.
- **Bulk mode**: up to 50 PDF URLs in one run, one result object per document.
- **Fail-soft**: one bad URL never fails the run — it returns `{ok: false, error}` and is **never charged**.
- **No size panic on long documents**: a PDF whose text is too large for a dataset row
  (think 2,000+ pages) still succeeds — the complete text is stored in the run's
  key-value store with a direct `textUrl`, and the row keeps a 500,000-character preview inline.

### Who this is for

- **AI / RAG engineers** feeding PDFs into embeddings, vector stores, or LLM context —
  the `text` field is exactly the string you chunk.
- **Agent builders** whose agent gets handed a PDF link mid-task and needs the contents
  as JSON, via API or Apify MCP.
- **Research and legal workflows** bulk-converting papers, filings, or contracts into
  searchable text with author/date metadata attached.
- **Automation builders** (Make, Zapier, n8n) who need "PDF in, text out" as one hosted step.

### Input

| Field | Type | Default | What it does |
|---|---|---|---|
| `url` | string | current public IRS Form 1040 | One PDF URL to extract |
| `urls` | string\[] | string | `[]` | More PDF URLs. A plain string is split on commas/newlines |
| `maxPdfs` | integer | `25` | Cap per run (hard max 50). Extra URLs are ignored, not charged |
| `maxOcrPages` | integer | `20` | Per-document cap on image-only pages sent through OCR (hard max 100) |
| `maxOcrPagesPerRun` | integer | `100` | Run-wide OCR cap across all PDFs (hard max 500) |

Provide `url` or `urls`. When `urls` is present, it is used alone and the schema's prefilled `url` is
ignored. Duplicates are removed and order is kept. PDFs are capped at
\~20 MB each with a 30-second fetch timeout. **With no URL at all the run reads the current public
IRS Form 1040 so the acceptance run uses a live source; that prefilled document is not charged.**

### Output fields

One dataset item per PDF:

| Field | Meaning |
|---|---|
| `url` | The URL you supplied |
| `ok` | `true` on success, `false` on a failure (never charged) |
| `pages` | Page count |
| `version` | PDF format version, from the info dictionary or the file header |
| `characters` | Length of the extracted text |
| `scanned` / `textSource` | Whether image-only content was detected, and whether text came from `text-layer`, `ocr`, or `mixed` pages |
| `ocrPagesOcred` / `ocrPagesDetected` | Image-only pages OCR'd and total image-only pages detected |
| `ocrTruncated` | `true` when the per-document or configured run-wide OCR cap stopped further OCR |
| `mixedDocument` | `true` when one PDF contained both text-layer and image-only pages |
| `info.title` / `author` / `subject` / `keywords` / `creator` / `producer` | Document metadata, `null` when absent |
| `info.creationDate` / `modificationDate` | Raw PDF date strings, e.g. `D:20260102072431-06'00'` |
| `info.createdAt` / `modifiedAt` | The same dates normalized to ISO 8601 |
| `text` | The full extracted text, in reading order |
| `textUrl` / `textKey` / `textTruncatedInline` | Only on huge documents: the complete text parked in the key-value store |
| `error` | Present with `ok:false` instead of the text when that URL failed |

### Examples

Both outputs below are from real runs of this actor, with `text` trimmed for space.

**1. A real form with full metadata**

Input:

```json
{ "url": "https://www.irs.gov/pub/irs-pdf/f1040.pdf" }
```

Output item:

```json
{
  "url": "https://www.irs.gov/pub/irs-pdf/f1040.pdf",
  "ok": true,
  "pages": 2,
  "version": "1.7",
  "characters": 9677,
  "info": {
    "title": "2025 Form 1040",
    "author": "C:DC:TS:CAR:MP",
    "subject": "U.S. Individual Income Tax Return",
    "keywords": "Fillable",
    "creator": "Designer 6.5",
    "producer": "Designer 6.5",
    "creationDate": "D:20260102072431-06'00'",
    "modificationDate": "D:20260102072431-06'00'",
    "createdAt": "2026-01-02T13:24:31.000Z",
    "modifiedAt": "2026-01-02T13:24:31.000Z"
  },
  "text": "Form\n1040 \n2025\nU.S. Individual Income Tax Return \nDepartment of the Treasury-Internal Revenue Service \nOMB No. 1545-0074 [...]"
}
```

Note `createdAt`: your pipeline gets a real ISO timestamp, not `D:20260102072431-06'00'`.

**2. A two-document batch**

Input:

```json
{ "urls": ["https://www.irs.gov/pub/irs-pdf/f1040.pdf", "https://www.archives.gov/files/press/press-releases/2015/images/letter-from-fdr.pdf"] }
```

The Actor returns one successful dataset item for each of those public documents.

### Call it from code

**curl** — synchronous run, extracted text straight back:

```bash
curl -X POST "https://api.apify.com/v2/acts/eliai~pdf-text-extractor/run-sync-get-dataset-items?token=${APIFY_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://www.irs.gov/pub/irs-pdf/f1040.pdf"}'
```

**Python** (`pip install apify-client`):

```python
import os
from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor("eliai/pdf-text-extractor").call(
    run_input={"urls": [
        "https://www.irs.gov/pub/irs-pdf/f1040.pdf",
        "https://www.archives.gov/files/press/press-releases/2015/images/letter-from-fdr.pdf",
    ]}
)
for doc in client.dataset(run["defaultDatasetId"]).iterate_items():
    if doc["ok"]:
        print(doc["url"], doc["pages"], "pages", doc["characters"], "characters")
```

**Node.js** (`npm install apify-client`):

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

if (!process.env.APIFY_TOKEN) throw new Error('APIFY_TOKEN is required');
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('eliai/pdf-text-extractor').call({
    url: 'https://www.irs.gov/pub/irs-pdf/f1040.pdf',
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items[0].text);
```

### Pricing

Pay per event, one event: `pdf-processed`.

| Event | What one event covers | Price |
|---|---|---|
| `pdf-processed` | **One PDF** downloaded and parsed — every page of it, text plus metadata | **$0.003** |

There is no per-run start charge, no monthly fee, and no per-page charge: a 2-page form and a
400-page manual both cost $0.003. 1,000 PDFs cost exactly $3.00. PDFs that fail (dead URL, not a
PDF, encrypted, oversized) are never billed, and neither is the prefilled IRS document.

Compared with other paid PDF text extractors on Apify (per-event prices read from the
Apify API, 2026-08-14):

| Actor | Start fee | Per PDF |
|---|---|---|
| **This actor** | **$0** | **$0.003** — failures free |
| memo23/pdf-text-extractor | $0.005 | $0.005 (+$0.015 per OCR page) |
| gochujang/pdf-text-extractor | $0.001 | $0.02 (+$0.0005 per page) |
| santamaria-automations/pdf-extractor | $0.001 | $0.005 |

A single PDF costs $0.003 here vs $0.006–$0.021 (start fee + first document) on the
actors above; there is no start fee to amortize, so the price is the same at every batch size.

### Automate it

Everything the Apify platform offers works here with zero extra code: **schedule** a
recurring extraction, fire a **webhook** when a run finishes, or drop it into **Make,
Zapier, or n8n** with the standard Apify app — pass the JSON input above and consume the
dataset items downstream. Agents can call it directly over **Apify MCP**.

#### It tells you whether the document actually changed

Point it at a PDF that gets re-published — a policy, a price list, a filing, a regulatory
notice — and every run reports whether the text moved since the last one:

| field | meaning |
|---|---|
| `isBaselineRun` | `true` on the first run for a URL; the baseline was just recorded |
| `changed` | `true` when the extracted text differs from the previous run |
| `changeSummary` | one line you can put straight into an alert |
| `trackingPersists` | `false` if your plan could not open a named store, so every run reads as a first run |

The comparison is on the **extracted text** only — not the page count, PDF version or
metadata, and not which path produced it. A publisher re-exporting a byte-different but
textually identical file does not report a change, and a document that flips between a
text layer and OCR between runs does not either.

Practical use: schedule it, add a webhook, and act only when `changed` is `true` — so a
quietly amended document surfaces the day it is edited instead of whenever someone
happens to re-read it.

### Scanned PDFs (OCR)

A scanned PDF is an image of a page with no text layer, and a plain extractor returns nothing for
it -- the single most common reason PDF extraction "silently fails". This Actor now detects that and
reads the page with OCR.

- **Detection is automatic and page-level:** each page with an embedded image but fewer than five
  extractable text characters is routed through OCR. Text-layer pages in the same PDF stay native,
  while truly blank pages are not OCR'd.
- **Every record says which path produced the text**, so you always know what you paid for:
  `scanned` (true/false), `textSource` (`ocr`, `mixed`, or `text-layer`), `ocrPagesOcred`,
  `ocrPagesDetected`, `ocrTruncated`, and `mixedDocument`.
- **`maxOcrPages`** caps how many scanned pages are read per document (default 20), so a 400-page
  scan cannot run away with your budget. `maxOcrPagesPerRun` exposes the second, run-wide cap
  (default 100, hard max 500).
- **Born-digital pages are never rasterised or sent to Tesseract.** They keep the base price and
  never incur an OCR event.

**Pricing note, stated plainly:** the per-page OCR charge (`ocr-page`, $0.015) cannot be activated
until **7 September 2026**, because Apify permits one pricing change per Actor per month and this
Actor has already used its slot. Until then **scanned pages are extracted and NOT billed** -- you
get the capability at the base price. Activation is planned for that date and is not automatic or
retroactive.

### When NOT to use this

- **You need tables preserved as tables.** You get reading-order text, not Markdown tables or
  cell structure. Financial statements will read as a stream of numbers.
- **You need the layout, fonts, coordinates, or images.** This returns text and metadata only.
- **You need to fill in or edit a PDF.** Read-only extraction; nothing is written back.
- **The file is password-protected, or behind a login.** Encrypted PDFs fail (uncharged), and
  only public URLs you supply are fetched — no credentials, no cookies.
- **You have the PDF locally, not online.** The input is a URL. Host it somewhere reachable first.

### Limits (honest ones)

- Text extraction from born-digital PDFs, plus OCR on scanned/image-only pages (capped by
  `maxOcrPages`, default 20 per document, and `maxOcrPagesPerRun`, default 100 per run).
  Born-digital pages never rasterise.
- 20MB per PDF, 50 PDFs per run, 30-second fetch timeout per URL.
- Password-protected PDFs fail (uncharged).
- The URL must serve the PDF bytes directly (redirects are followed; HTML viewer pages are not PDFs).
- Layout is not reconstructed — you get reading-order text, not Markdown tables.
- Form *fields* are not read as key/value pairs; a fillable form returns its printed labels as text.

### FAQ

#### How do I extract text from a PDF by URL, without installing anything?

Pass the URL as `url` and run it. You get the full text as a JSON string plus page count and
document metadata. No Python, no poppler, no local dependency to pin.

#### Does it work on scanned PDFs?

Yes. Image-only pages are rasterised and read with Tesseract, including those inside a PDF that
also has text-layer pages. Born-digital pages never take that path. Until 2026-09-07 the `ocr-page`
event cannot be priced (one pricing write per Actor per month, already used), so scanned pages are
extracted at the base $0.003. Charging at $0.015 per OCR page is planned on or after that date.

#### What happens with very large PDFs?

They succeed. If the extracted text is too big for an Apify dataset row (~9MB), the run
stores the complete text in its key-value store and the dataset item carries a `textUrl`
to download it, plus the first 500,000 characters inline as a preview. You never lose
the expensive extraction to a storage limit.

#### How am I billed, exactly?

$0.003 per PDF that parses successfully — the `pdf-processed` event. Failed URLs, non-PDFs,
encrypted or oversized files produce `{ok: false}` records and cost nothing. There is no
start fee and no monthly fee.

#### Can I extract text from many PDFs at once?

Yes — up to 50 URLs in one run via `urls` (default cap 25, raise with `maxPdfs`). Each PDF is
its own dataset item, and one bad link never stops the others.

#### How do I get a PDF's title, author, and creation date?

They are in the `info` object of every successful record, with the dates given twice: raw PDF
format (`creationDate`) and normalized ISO 8601 (`createdAt`). Fields the document does not
carry come back as `null`.

#### Can I use this for RAG or to feed a vector database?

That is the main use. The `text` field is the exact string to chunk and embed; `pages`,
`characters` and `info` give you the metadata to attach to each chunk. Failures are explicit
`ok:false` rows, so a broken source URL never silently poisons an index.

#### Is my PDF stored anywhere?

The document is fetched, parsed in memory, and the result written to **your** run's dataset on
your own Apify account. Delete the run and the output goes with it.

#### Can an AI agent use this?

Yes — it is callable over Apify MCP as an agent tool. Input `{ "url": "<pdf url>" }`,
returns text + metadata as JSON. If your agent can receive a link, it can now read the document.

### For agents and automation

- **Capability:** fetch one or many PDF URLs and return extracted text + metadata as JSON
- **Required input:** `url` or `urls`
- **Returns:** one JSON record per PDF; `text` holds the full extracted text
- **Bounded:** `maxPdfs` caps the run; failures isolate per document
- **Side effects:** none

### For AI agents

This Actor is built to be called by software, not just by people.

- **Mount it directly as an MCP tool** — no Store search, no ranking, just this one tool:
  `https://mcp.apify.com/?actors=eliai/pdf-text-extractor`
- **Or call it over HTTP** and get the results in the same request:
  `POST https://api.apify.com/v2/acts/eliai~pdf-text-extractor/run-sync-get-dataset-items`
- **Pay with x402, without an Apify account.** This Actor is whitelisted for agentic payments, so an agent holding USDC on Base can buy a prepaid token and spend it here. The minimum purchase is $1, the token balance is an absolute spending cap, and it expires 14 days after purchase.
- **Costs are predictable before you call.** Pricing is pay-per-event (see Pricing above), so an agent can budget a run in advance instead of discovering the bill afterwards.
- **Send only the field you mean.** If you pass the bulk field, it is used on its own; the single-value field is a fallback, never merged into your request. You are charged for the items you sent and nothing else.

### Changelog

- **2026-08-28:** Every run now reports whether the document's text CHANGED since the last
  run for that URL (`changed`, `isBaselineRun`, `changeSummary`, `trackingPersists`). The
  comparison is on extracted text only, so a re-export that is byte-different but textually
  identical does not report a change. Nothing was removed and prices are unchanged — schedule
  the Actor and act only when `changed` is true.

- **2026-08-27:** OCR routing is now page-level, including mixed PDFs; default-input billing is
  explicitly suppressed; OCR execution is bounded per document and per run via `maxOcrPages` and
  `maxOcrPagesPerRun`; charge results use Apify's returned `chargedCount`; and OCR provenance
  fields are visible in the dataset table. Current prices are unchanged.

# Actor input Schema

## `url` (type: `string`):

A direct public PDF URL. Text-layer pages are extracted natively; image-only pages are read with OCR.

## `urls` (type: `array`):

A list of PDF URLs to process in one run. When you set this, it is used on its own and the single-value field above is ignored, so you are only charged for the items you sent.

## `maxPdfs` (type: `integer`):

Maximum number of PDFs to process in a single run.

## `maxOcrPages` (type: `integer`):

Cap on how many SCANNED pages to run OCR on per document. Born-digital PDFs never use OCR and are never charged for it.

## `maxOcrPagesPerRun` (type: `integer`):

Run-wide OCR work cap across all PDFs. If reached, later image-only pages are reported by ocrPagesDetected and ocrTruncated instead of being silently processed.

## Actor input object example

```json
{
  "url": "https://www.irs.gov/pub/irs-pdf/f1040.pdf",
  "urls": [
    "https://www.irs.gov/pub/irs-pdf/f1040.pdf"
  ],
  "maxPdfs": 25,
  "maxOcrPages": 20,
  "maxOcrPagesPerRun": 100
}
```

# Actor output Schema

## `results` (type: `string`):

Every item this run produced, as JSON.

## `resultsCsv` (type: `string`):

The same items as a spreadsheet-ready CSV.

# 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 = {
    "url": "https://www.irs.gov/pub/irs-pdf/f1040.pdf",
    "urls": [
        "https://www.irs.gov/pub/irs-pdf/f1040.pdf"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("eliai/pdf-text-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 = {
    "url": "https://www.irs.gov/pub/irs-pdf/f1040.pdf",
    "urls": ["https://www.irs.gov/pub/irs-pdf/f1040.pdf"],
}

# Run the Actor and wait for it to finish
run = client.actor("eliai/pdf-text-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 '{
  "url": "https://www.irs.gov/pub/irs-pdf/f1040.pdf",
  "urls": [
    "https://www.irs.gov/pub/irs-pdf/f1040.pdf"
  ]
}' |
apify call eliai/pdf-text-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,eliai/pdf-text-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/XZQNvopPVL9ewsUXK/builds/uygfiAbeU2twBhv3h/openapi.json
