# PDF to Markdown, Tables & OCR (`nichedata-lab/pdf-extract`) Actor

Extract text, Markdown, per-page text, metadata, and tables from PDF URLs, uploads, or base64. Image-only pages are read with English or Japanese OCR. Failed PDFs are not charged. Standby MCP tools extract a PDF or its tables.

- **URL**: https://apify.com/nichedata-lab/pdf-extract.md
- **Developed by:** [nichedata-lab](https://apify.com/nichedata-lab) (community)
- **Categories:** AI, Developer tools, MCP servers
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.00 / 1,000 pdf processeds

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

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

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## 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.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## PDF Text, Tables, and OCR

Extract text, Markdown, per-page text, document metadata, and tables from PDFs. Send URLs, upload files, or pass base64. Pages with no text layer are read with OCR. The same Actor is an [MCP server](https://docs.apify.com/sdk/python/docs/guides/mcp-servers) in Standby mode, so an agent can extract one PDF or pull its tables.

The Actor downloads only the PDF URLs in the input. It does not crawl sites, follow links, or use a proxy.

### Use cases

- Turn a report or paper into plain text and Markdown for retrieval-augmented generation.
- Pull ruled tables out as JSON and as CSV, with a key-value store file for each table.
- Read a scanned page in English or Japanese when that page has no text layer.
- Keep a failed download or a broken file in the dataset without paying the per-PDF charge.

### How to run it

The prefilled input reads the U.S. Bureau of Labor Statistics CPI news release, which is a public PDF with tables. Start the Actor with that input, or replace the URL with your own file.

| Input | What it does |
| --- | --- |
| PDF URLs | `http` or `https` links. Each file is downloaded once. Redirects are followed. |
| Upload PDF files | Files stored in a key-value store. The form passes each record key. API calls can also pass `https://api.apify.com/v2/key-value-stores/{storeId}/records/{key}` or `key-value-store://{storeId}/{key}`. |
| Base64 PDFs | A base64 string, a data URI, or `{"filename": "notes.pdf", "data": "..."}`. |
| Page range | `1-5, 8, 12-`. `12-` means page 12 through the end. Empty reads every page, up to the run limit. |
| OCR mode | `auto` reads a page with OCR only when it has no letters or digits in the text layer. `always` reads every selected page with OCR. `never` skips OCR. |
| OCR languages | `eng`, `jpn`, and `jpn_vert`. Use `jpn_vert` for vertical Japanese. Combine codes when a scan mixes them. |
| Max OCR pages per PDF | Stops OCR after this many pages in one file. `0` turns OCR off. Default 20. Hard cap 40. |
| Full text / Markdown / Per-page text / Tables | Turn a field off to shrink the dataset row. Counts are still saved. |
| Maximum PDFs | Default 10. Hard cap 25. |
| Maximum file size | Default 20 MB. Hard cap 32 MB. Larger files are failed rows. |
| Maximum pages per run | Default 60. Hard cap 120. Shared across every PDF in the run. |
| Download timeout | Default 45 seconds per URL. |

Example: the first two pages of a public PDF, with tables and no OCR.

```json
{
  "pdfUrls": ["https://www.bls.gov/news.release/pdf/cpi.pdf"],
  "pageRange": "1-2",
  "ocrMode": "never",
  "includeTables": true
}
```

Example: a Japanese scan, OCR only.

```json
{
  "pdfUrls": ["https://example.com/scan.pdf"],
  "ocrMode": "auto",
  "ocrLanguages": ["jpn_vert"],
  "maxOcrPagesPerPdf": 10
}
```

### Output

Each dataset item is one PDF. `status` is `succeeded` or `failed`. A failed row has `error` set and the text fields null. `metadata.author` is the author string stored in the PDF, unchanged.

`pages[].ocr` is true when that page's text came from OCR. In `auto` mode that is only a page whose text layer has no letters or digits, so a page number or a header is enough to skip OCR. Use `always` when a scan also has a junk text layer.

Tables come from ruling lines on the page, not from OCR. A scanned table without lines in the text layer is not reconstructed. Each table has `rows`, a `csv` string, and `csvKey` / `csvUrl` for the copy in the run key-value store.

```json
{
  "source": "sample.pdf",
  "sourceType": "file",
  "status": "succeeded",
  "error": null,
  "title": "Sample parcel list",
  "pageCount": 3,
  "extractedPageCount": 3,
  "metadata": {
    "title": "Sample parcel list",
    "author": null,
    "subject": null,
    "keywords": null,
    "creator": null,
    "producer": null,
    "creationDate": null,
    "modificationDate": null
  },
  "text": "The parcel holds six green boxes.\n\nBETA TEXT PAGE",
  "markdown": "# Sample parcel list\n\n## Page 1\n\nThe parcel holds six green boxes.\n\n### Tables\n\n| Item | Count |\n| --- | --- |\n| Box | 6 |\n| Crate | 2 |",
  "pages": [
    { "pageNumber": 1, "text": "The parcel holds six green boxes.", "ocr": false, "charCount": 34 },
    { "pageNumber": 3, "text": "SCANNED PAGE GAMMA", "ocr": true, "charCount": 18 }
  ],
  "tables": [
    {
      "pageNumber": 1,
      "tableIndex": 0,
      "rows": [["Item", "Count"], ["Box", "6"], ["Crate", "2"]],
      "rowCount": 3,
      "columnCount": 2,
      "csv": "Item,Count\nBox,6\nCrate,2\n",
      "csvKey": "table-0-p1-t0.csv",
      "csvUrl": "https://api.apify.com/v2/key-value-stores/STORE/records/table-0-p1-t0.csv"
    }
  ],
  "tableCount": 1,
  "ocrPageCount": 1,
  "ocrPageNumbers": [3],
  "charCount": 120,
  "limitNote": null
}
```

The dataset view **Overview** shows the source, status, title, page counts, table count, OCR page count, character count, and error.

Cell text longer than 2000 characters is cut. OCR of one page gives up after 45 seconds. A page that times out is saved with its text layer (often empty) and is not an `ocr-page` charge. The Tesseract process group is killed when the timeout fires.

### MCP server

In Standby mode the Actor serves the MCP endpoint at `/mcp` (Streamable HTTP). `webServerMcpPath` is `/mcp`. A client connects to the Actor's Standby URL with an Apify API token:

```json
{
  "mcpServers": {
    "pdf-extract": {
      "url": "https://<username>--pdf-extract.apify.actor/mcp",
      "headers": {
        "Authorization": "Bearer <APIFY_API_TOKEN>"
      }
    }
  }
}
```

`GET /` answers the platform readiness probe.

| Tool | What it returns |
| --- | --- |
| `extract_pdf` | Text, Markdown, metadata, and a short preview of each page. At most 12 pages and 4 OCR pages. Long text is truncated and the reply says so. |
| `extract_tables` | Up to 6 tables, 20 rows and 12 columns each. `ocr_mode` defaults to `never` because tables are read from the PDF's lines, not from OCR. |

Pass `url` or `base64_pdf`, not both. A resource at `resource://pdf-extract/about` describes OCR and billing. Reading it is not a charged tool call.

### Pay per event

A dataset run charges `actor-start` once. Each PDF that extracts successfully charges `pdf-processed`. Each page that was actually read with OCR then charges `ocr-page`. A download error, a file that is not a PDF, and a PDF that cannot be opened are saved as failed rows and do not charge `pdf-processed` or `ocr-page`.

An MCP call charges `mcp-tool-call` after the arguments are validated. If the PDF then succeeds, it also charges `pdf-processed` and `ocr-page`. A failed PDF does not charge those two events.

Proposed prices are in [PRICING.md](PRICING.md). They are not written into the Actor configuration, so pushing this source does not publish a price. In Apify Console, add the four event names from that file, mark `pdf-processed` as the primary event, and remove the synthetic `apify-default-dataset-item` and `apify-actor-start` events. The dataset-item event would bill failed rows. The synthetic start event would bill a second start fee on top of `actor-start`.

On a multi-tenant Standby run, charges pass the `X-Actor-Request-ID` header as `request_id`, which is how the platform bills the caller of a shared run.

### Limits

- At most 25 PDFs, 32 MB each, and 120 pages per run. Defaults are 10 PDFs, 20 MB, and 60 pages. OCR is capped at 40 pages per PDF (default 20).
- PDFs are read one at a time. A normal page is rendered at about 150 DPI. A scan whose page is thousands of points wide is capped at 2800 pixels on the long edge. Tesseract runs as one thread, because a 1024 MB Apify run has about a quarter of a core while `nproc` still reports the host.
- The Actor does not send files through a proxy and does not read environment proxy variables for the download.
- Run memory: 1024 MB minimum and default, 4096 MB maximum. At that quota the 10-page English patent took 57 seconds. At 2048 MB it took 28 seconds, and the cost per page was about the same. See PRICING.md.
- Give a text run a few minutes of platform timeout. Give an OCR run about 10 minutes for the 40-page cap (about 6 seconds per page at 1024 MB). The Actor definition does not set a timeout.

### Libraries and licenses

Text, metadata, and page rendering use [pypdfium2](https://github.com/pypdfium2-team/pypdfium2) (Apache-2.0 OR BSD-3-Clause). The wheels bundle PDFium, which is BSD-3-Clause, plus the dependency notices shipped inside the wheel. Tables use [pdfplumber](https://github.com/jsvine/pdfplumber) (MIT) and its dependency pdfminer.six (MIT). OCR uses the Tesseract engine (Apache-2.0) with the `eng`, `jpn`, and `jpn_vert` traineddata files (Apache-2.0). `jpn_vert.traineddata` is 2.9 MB. Images are decoded with Pillow (HPND).

PyMuPDF is not used. PyMuPDF is AGPL-3.0 unless you buy a commercial license from Artifex, which is a poor fit for a Store Actor that serves other users. pypdfium2 renders pages under a permissive license instead.

### Local development

Python 3.11 or newer, plus Tesseract with English and Japanese traineddata. On Debian or Ubuntu:

```bash
sudo apt-get install -y tesseract-ocr tesseract-ocr-eng tesseract-ocr-jpn tesseract-ocr-jpn-vert
```

From this directory:

```bash
python -m venv .venv
.venv/bin/pip install -r requirements.txt -r requirements-dev.txt
.venv/bin/pytest
```

`pytest` builds nothing from the network. It uses the small PDFs in `tests/fixtures/`, including a ruled table, an image-only page, and a Japanese image-only page. One test runs the Actor locally and checks that a broken PDF is not charged.

To run the dataset Actor yourself, write the input to the local key-value store and disable the storage purge so that file is still there when the run starts:

```bash
mkdir -p storage/key_value_stores/default
cp examples/default-input.json storage/key_value_stores/default/INPUT.json
APIFY_PURGE_ON_START=false ACTOR_TEST_PAY_PER_EVENT=true python -m pdf_extract_actor
```

Rows are written under `storage/datasets/default/`. Table CSV files are written under `storage/key_value_stores/default/`. With `ACTOR_TEST_PAY_PER_EVENT=true`, charges are logged under `storage/datasets/charging-log/` and nothing is billed.

Cloud build, `apify push`, Standby hosting, and Console monetization need an Apify account token. This package does not call `apify push`.

### FAQ

**Why did a scanned page come back empty?** `auto` skips OCR when the page already has any letter or digit, including a page number. Set `ocrMode` to `always`. For vertical Japanese, set the language to `jpn_vert`. A page that exceeds 45 seconds is recorded as an OCR failure and is not charged.

**Why are there no tables on a scan?** Tables are detected from lines in the PDF, not from the OCR text. A photograph of a table needs a text layer or ruling lines.

**Are failed files billed?** The run still charges `actor-start` when it begins. The failed file does not charge `pdf-processed` or `ocr-page`. An MCP call still charges `mcp-tool-call` because the tool ran; the failed file does not add the PDF or OCR events.

**Which memory setting should I pick?** 1024 MB. That is the minimum and the default. A single Tesseract thread does not go faster in proportion to a larger CPU quota, so 2048 MB costs about the same per OCR page. Details are in PRICING.md.

# Actor input Schema

## `pdfUrls` (type: `array`):

Direct http or https links to PDF files. Each URL is downloaded once. Redirects are followed.

## `pdfFiles` (type: `array`):

PDF files uploaded to a key-value store. The form stores each file and passes its record key. API calls may also pass an https://api.apify.com/v2/key-value-stores/{storeId}/records/{key} URL or key-value-store://{storeId}/{key}.

## `base64Pdfs` (type: `array`):

For API calls. Each item is a base64 string, a data-URI, or an object {"filename": "notes.pdf", "data": "..."}.

## `pageRange` (type: `string`):

Pages to read, counted from 1. Examples: 1-5, 8, 12-. 12- means page 12 through the end. Leave empty to read every page, up to the run page limit.

## `ocrMode` (type: `string`):

auto OCRs image-only pages. always OCRs every selected page. never skips OCR.

## `ocrLanguages` (type: `array`):

Tesseract language codes. English, horizontal Japanese, and vertical Japanese are installed. Use jpn_vert for vertical writing. Combine codes when a scan mixes them.

## `maxOcrPagesPerPdf` (type: `integer`):

Upper bound on pages sent to OCR inside one PDF. Further pages keep their text layer. 0 disables OCR for the run.

## `includeText` (type: `boolean`):

Include the plain text of the selected pages in the text field.

## `includeMarkdown` (type: `boolean`):

Include Markdown with a heading per page, an OCR note on OCR pages, and tables as Markdown tables.

## `includePages` (type: `boolean`):

Include a pages array. Each page has its text and whether OCR was used.

## `includeTables` (type: `boolean`):

Include ruled tables as JSON rows and CSV. Each CSV is also stored in the key-value store.

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

How many documents this run accepts. The hard cap is 25.

## `maxFileSizeMb` (type: `integer`):

Larger files are saved as failed rows and are not charged. The hard cap is 32 MB.

## `maxPagesPerRun` (type: `integer`):

Total pages read across every PDF. The hard cap is 120. Later pages are skipped and the row explains the limit.

## `downloadTimeoutSecs` (type: `integer`):

Time allowed to download one PDF URL.

## Actor input object example

```json
{
  "pdfUrls": [
    "https://www.bls.gov/news.release/pdf/cpi.pdf"
  ],
  "pageRange": "",
  "ocrMode": "auto",
  "ocrLanguages": [
    "eng"
  ],
  "maxOcrPagesPerPdf": 20,
  "includeText": true,
  "includeMarkdown": true,
  "includePages": true,
  "includeTables": true,
  "maxPdfs": 10,
  "maxFileSizeMb": 20,
  "maxPagesPerRun": 60,
  "downloadTimeoutSecs": 45
}
```

# Actor output Schema

## `overview` (type: `string`):

One row per PDF, including failed files.

# 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 = {
    "pdfUrls": [
        "https://www.bls.gov/news.release/pdf/cpi.pdf"
    ],
    "pageRange": "",
    "ocrMode": "auto",
    "ocrLanguages": [
        "eng"
    ],
    "maxOcrPagesPerPdf": 20,
    "includeText": true,
    "includeMarkdown": true,
    "includePages": true,
    "includeTables": true
};

// Run the Actor and wait for it to finish
const run = await client.actor("nichedata-lab/pdf-extract").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 = {
    "pdfUrls": ["https://www.bls.gov/news.release/pdf/cpi.pdf"],
    "pageRange": "",
    "ocrMode": "auto",
    "ocrLanguages": ["eng"],
    "maxOcrPagesPerPdf": 20,
    "includeText": True,
    "includeMarkdown": True,
    "includePages": True,
    "includeTables": True,
}

# Run the Actor and wait for it to finish
run = client.actor("nichedata-lab/pdf-extract").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 '{
  "pdfUrls": [
    "https://www.bls.gov/news.release/pdf/cpi.pdf"
  ],
  "pageRange": "",
  "ocrMode": "auto",
  "ocrLanguages": [
    "eng"
  ],
  "maxOcrPagesPerPdf": 20,
  "includeText": true,
  "includeMarkdown": true,
  "includePages": true,
  "includeTables": true
}' |
apify call nichedata-lab/pdf-extract --silent --output-dataset

```

## MCP server setup

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

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/a1jfGngMaC0Mxjhyd/builds/xd7u3E4SiwiYPBaFr/openapi.json
