# PDF to Markdown, Tables & RAG Chunks (with OCR) (`errandkit/pdf-to-markdown-tables`) Actor

Convert PDF, DOCX and image files to clean Markdown, tables as CSV and RAG-ready chunks with page numbers. Scanned pages are read with OCR. No API keys, pay per page, built for AI agents and LLM pipelines.

- **URL**: https://apify.com/errandkit/pdf-to-markdown-tables.md
- **Developed by:** [Killis Haraway](https://apify.com/errandkit) (community)
- **Categories:** AI, Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 page processed (text layer)s

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?

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 to Markdown, Tables & RAG Chunks (with OCR)

Turn **PDF, Word (DOCX) and image files** into clean **Markdown**, **tables (rows + CSV)** and **RAG-ready chunks with page numbers**. Scanned pages are read automatically with OCR. No API keys, no LLM calls, nothing to configure. You pay a fraction of a cent per page.

Built for AI agents and LLM pipelines: give it links (or upload a file), get back text your model can actually use.

### What you get for each document

| Field | What it is |
|---|---|
| `markdown` | The whole document as Markdown: headings (`#`, `##`), paragraphs, bullet lists, tables, and `<!-- page N -->` markers |
| `tables` | Every detected table with its `page`, `rows` (list of lists) and `csv` |
| `chunks` | Text split for embeddings: `text`, `page_start`, `page_end`, nearest `heading`, `char_count` |
| `metadata` | Title, author, subject, dates from the file properties |
| `page_count`, `pages_text`, `pages_ocr`, `pages_empty` | What was read and how |
| `warnings`, `error` | Plain-language notes and stable error codes (see below) |

Each document's Markdown is also saved as a `.md` file in the run's key-value store.

### Quick start

**In the Console:** paste one or more links into *Document URLs* (or upload a file) and click **Start**.

**API (Python):**

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("errandkit/pdf-to-markdown-tables").call(run_input={
    "documentUrls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"],
    "outputMode": "documents",
})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item["document_name"], item["page_count"], len(item["tables"]))
    print(item["markdown"][:500])
```

**RAG ingestion** (one dataset item per chunk, ready for a vector database):

```json
{
  "documentUrls": ["https://example.com/handbook.pdf", "https://example.com/policy.docx"],
  "outputMode": "chunks",
  "chunkMaxChars": 1200,
  "chunkOverlapChars": 150,
  "includeMarkdown": false
}
```

**Base64 input** (for agents and back ends that already hold the file):

```json
{"documents": [{"name": "invoice.pdf", "content_base64": "JVBERi0xLjcK..."}]}
```

### Use it from an AI agent (MCP)

This Actor works as a tool in Claude, Cursor, ChatGPT connectors and other MCP clients through Apify's MCP server:

```
https://mcp.apify.com/?actors=errandkit/pdf-to-markdown-tables
```

The agent passes a link, the Actor returns Markdown, tables and chunks. Results are JSON with stable field names, so agents don't have to guess.

### Input options

| Option | Default | Notes |
|---|---|---|
| `documentUrls` | – | Direct links to PDF, DOCX, PNG, JPEG, TIFF, GIF, BMP or WEBP files |
| `uploadedFile` | – | Upload one file in the Console |
| `documents` | – | JSON list of `{name, url}` or `{name, content_base64}` |
| `outputMode` | `documents` | `documents` = one item per file; `chunks` = one item per chunk |
| `pages` | all | PDFs only, e.g. `1-3,7` |
| `ocr` | `auto` | `auto` reads only pages without a text layer; `force` OCRs every page; `off` never |
| `ocrLanguage` | `eng` | `spa`, `fra`, `deu`, `por`, `ita`, or combined like `eng+spa` |
| `tables` | `true` | Detect ruled tables in PDFs; all DOCX tables are kept |
| `chunking`, `chunkMaxChars`, `chunkOverlapChars` | `true`, 1500, 150 | Chunks keep the nearest heading and page range; tables are split by rows with the header repeated |
| `includeMarkdown` | `true` | Turn off to keep items small |
| `saveMarkdownFiles` | `true` | Save `001-name.md` files to the key-value store |
| `maxPagesPerDocument` | 500 | Pages after this are skipped and not charged |
| `failOnEmpty` | `true` | Mark the run failed if no document has any text |

### Pricing

Pay per event. You only pay for pages that produced text.

| Event | Price | Per 1,000 |
|---|---|---|
| Page processed (text layer; DOCX counts 1 page per 3,000 characters) | $0.0005 | $0.50 |
| Page or image read with OCR | $0.003 | $3.00 |
| Actor start (Apify standard) | $0.00005 | $0.05 |

Examples: a 10-page digital PDF costs **$0.005**; a 10-page scan costs **$0.03**. Blank pages, failed downloads, encrypted or broken files are **not charged**. Set *Maximum cost per run* and the Actor stops before going over it, keeping everything already finished.

### Error codes

Every failed document gets an item with `status: "error"` and one of these codes. One bad file never stops the rest of the batch.

| Code | Meaning |
|---|---|
| `DOWNLOAD_FAILED` | The link returned an error (the HTTP status is included) or timed out |
| `URL_NOT_ALLOWED` | Not http(s), or points to a private network address |
| `UNSUPPORTED_FORMAT` | Not a PDF, DOCX or image (for example an HTML page, a ZIP, legacy .doc, or an Excel file) |
| `FILE_TOO_LARGE` | Over 100 MB |
| `PDF_ENCRYPTED` | Password-protected PDF |
| `PDF_CORRUPT`, `DOCX_CORRUPT`, `IMAGE_CORRUPT` | The file is damaged |
| `PAGE_RANGE_INVALID` | `pages` could not be parsed |
| `OCR_LANGUAGE_UNAVAILABLE` | Unknown OCR language code |
| `NO_TEXT_FOUND` | No text on any page (and OCR off, or the scan is unreadable) |
| `MAX_COST_REACHED` | Your maximum cost per run was reached |

The run summary (`OUTPUT` in the key-value store) lists totals, the codes seen and the exact pages charged.

### Good to know

- **Tables:** PDF tables are found from their drawn cell borders. Tables made only of aligned text (no lines) come through as text paragraphs.
- **Columns:** two-column pages are read left column first, then right. Complex magazine layouts may still mix.
- **OCR quality** depends on the scan. 200 dpi Tesseract works well on typed documents, poorly on handwriting.
- **Not supported:** password-protected PDFs, legacy `.doc`, PowerPoint, spreadsheets (use a spreadsheet tool), web pages.
- Typical speed: about 4 digital pages per second; about 1 OCR page per second.

### Privacy

Files are processed in memory inside your own Apify run. Nothing is sent to any third-party service or AI model, and nothing is kept by the developer. Output lives in your run's storage under your account and retention settings.

### Feedback

Found a document that converts badly? Open an issue on the Actor's *Issues* tab with a public link to it.

Part of the Errandkit catalog of data tools, APIs and MCP servers for AI agents: https://errandkit.com

# Actor input Schema

## `documentUrls` (type: `array`):

Public links to PDF, DOCX or image files (PNG, JPEG, TIFF, GIF, BMP, WEBP). Use the direct file link, not a viewer page.

## `uploadedFile` (type: `string`):

Upload one PDF, DOCX or image from your computer.

## `documents` (type: `array`):

For API and agent use: \[{"name": "a.pdf", "url": "https://..."}] or \[{"name": "a.pdf", "content_base64": "..."}].

## `outputMode` (type: `string`):

documents: one dataset item per document (Markdown, tables, chunks, metadata). chunks: one item per chunk, ready for a vector database.

## `pages` (type: `string`):

Page selection, 1-based, e.g. 1-3,7. Leave empty for all pages.

## `ocr` (type: `string`):

auto: OCR only pages without a text layer (scans). force: OCR every page. off: never (scanned pages come back empty).

## `ocrLanguage` (type: `string`):

Tesseract language code. Combine with + (e.g. eng+spa).

## `tables` (type: `boolean`):

Detect tables with drawn cell borders in PDFs (and all DOCX tables) and return them as rows and CSV.

## `chunking` (type: `boolean`):

Split each document into chunks that keep the nearest heading and the page range.

## `chunkMaxChars` (type: `integer`):

Target maximum characters per chunk.

## `chunkOverlapChars` (type: `integer`):

Characters repeated from the end of the previous chunk.

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

Turn off to keep dataset items small when you only need chunks or tables.

## `saveMarkdownFiles` (type: `boolean`):

Also save each document's Markdown as a file in the key-value store.

## `maxPagesPerDocument` (type: `integer`):

Pages beyond this are skipped (and not charged).

## `failOnEmpty` (type: `boolean`):

Marks the run failed (not succeeded-but-empty) when no document yields any text.

## Actor input object example

```json
{
  "documentUrls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
  ],
  "outputMode": "documents",
  "ocr": "auto",
  "ocrLanguage": "eng",
  "tables": true,
  "chunking": true,
  "chunkMaxChars": 1500,
  "chunkOverlapChars": 150,
  "includeMarkdown": true,
  "saveMarkdownFiles": true,
  "maxPagesPerDocument": 500,
  "failOnEmpty": true
}
```

# Actor output Schema

## `documents` (type: `string`):

No description

## `summary` (type: `string`):

No description

## `files` (type: `string`):

No description

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

// Run the Actor and wait for it to finish
const run = await client.actor("errandkit/pdf-to-markdown-tables").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 = { "documentUrls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"] }

# Run the Actor and wait for it to finish
run = client.actor("errandkit/pdf-to-markdown-tables").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 '{
  "documentUrls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
  ]
}' |
apify call errandkit/pdf-to-markdown-tables --silent --output-dataset

```

## MCP server setup

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

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/d8k3BBVhxbU2QiVrF/builds/YJvrfceHCalMfdtxF/openapi.json
