# PDF to Markdown Extractor - RAG Chunks (`pgrillo/pdf-to-markdown-extractor`) Actor

Extract clean Markdown text from PDF files. Preserves tables, removes running headers and footers, keeps correct reading order, and splits into RAG-ready chunks that never cut mid-sentence. Built for LLM ingestion, vector databases and AI knowledge bases.

- **URL**: https://apify.com/pgrillo/pdf-to-markdown-extractor.md
- **Developed by:** [Peter Grillo](https://apify.com/pgrillo) (community)
- **Categories:** Developer tools, AI
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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

## Document to RAG-Ready Markdown

Turn PDFs into clean markdown and retrieval-ready chunks. Built for people
feeding institutional documents into RAG pipelines and LLMs.

### Why this instead of a plain text extractor

Naive PDF text extraction produces text that *looks* fine and then quietly
poisons a RAG index: running headers repeat on every chunk, tables collapse
into unreadable word soup, and chunks get cut in the middle of sentences.

Measured against naive extraction (PyMuPDF `get_text`) on the same documents:

| Document | Metric | Naive | This actor |
|---|---|---|---|
| IRS Form 1040 instructions (126 pp) | chunks cut mid-sentence | 468 / 733 | **37 / 740** |
| IRS Form 1040 instructions | tables recovered as markdown | 0 | **89** |
| IRS Form 1040 instructions | fragmented lines | 20.5% | **14.7%** |
| NIST AI RMF (48 pp) | fragmented lines | 14.0% | **6.2%** |
| ResNet paper, 2-column (12 pp) | fragmented lines | 42.5% | **18.7%** |
| ResNet paper | tables recovered | 0 | **21** |
| YOLO paper, 2-column (10 pp) | fragmented lines | 37.9% | **20.5%** |
| BERT paper, 2-column (16 pp) | fragmented lines | 50.4% | **31.8%** |
| IRS Form 1040 instructions | token recall vs source | - | **99.2%** |

Sentence integrity (a stricter check: share of sentences that read as complete
and unbroken) is at parity with naive extraction on two-column papers —
96.5% vs 96.6% (ResNet), 92.1% vs 92.2% (YOLO), 85.5% vs 89.0% (BERT). We do
not claim to improve reading order; we claim cleaner structure at no cost to it.

Where it does **not** help: clean single-column academic papers. On one arXiv
paper our fragmentation was 8.2% vs naive 5.0% — if your corpus is single-column
preprints, a simple extractor is fine and you should save your money.

### What it does

- **Reading order** - detects two-column layouts and reads columns in order.
- **Boilerplate removal** - drops headers/footers that repeat across pages.
- **Tables as markdown** - table regions are excluded from body text, so
  tabular numbers don't contaminate prose.
- **Headings** - inferred from font size (not bold, which is used for emphasis).
- **De-hyphenation** - rejoins words and sentences broken across lines.
- **Chunking** - breaks on headings, never mid-sentence, with `section`,
  `page_start`, `page_end` metadata and configurable overlap.

### Limitations (please read before paying)

- **No OCR.** Scanned PDFs without a text layer produce little or no text. The
  run reports this in its status message.
- Complex multi-column tables and heavy visual layouts extract imperfectly.
- Verify output against the source before relying on it for anything
  consequential. See TERMS.md.

### Input

| Field | Type | Default | Notes |
|---|---|---|---|
| `pdfUrls` | array | - | Direct PDF links you have the right to process |
| `chunkSize` | int | 1800 | Target characters per chunk |
| `chunkOverlap` | int | 150 | Character overlap between chunks |
| `extractTables` | bool | true | Emit tables as markdown |
| `removeBoilerplate` | bool | true | Strip repeating headers/footers |
| `emitChunks` | bool | true | Chunks (true) or whole pages (false) |
| `maxPages` | int | 0 | 0 = all pages |

### Output

Chunk mode: `{source, section, page_start, page_end, chars, text}`
Page mode: `{source, page, columns, markdown, tables[]}`
Failures push `{source, error}` and are **not charged**.

### Pricing

Pay per event: **$0.02 per document** + **$0.001 per page**. You are charged
only for documents that extract successfully; failed URLs cost nothing.

### Licence

AGPL-3.0. This is a network service, so you are entitled to the Corresponding
Source: the complete source is at
https://github.com/petergrillo/doc-to-rag-markdown — see also LICENSE and NOTICE.
Uses PyMuPDF (AGPL-3.0 / Artifex commercial); not affiliated with Artifex.

# Actor input Schema

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

Direct links to PDF files you have the right to download and process. HTML pages, login walls and paywalled files are not supported.

## `chunkSize` (type: `integer`):

Target characters per chunk for RAG. Chunks break on headings and never mid-sentence.

## `chunkOverlap` (type: `integer`):

Characters of overlap carried from the end of one chunk into the next, to preserve context across boundaries.

## `extractTables` (type: `boolean`):

Recover tables as markdown and exclude their contents from body text, so tabular numbers do not contaminate prose.

## `removeBoilerplate` (type: `boolean`):

Strip running headers and footers that repeat on most pages (page numbers, document IDs).

## `emitChunks` (type: `boolean`):

If enabled, output retrieval-ready chunks with section and page metadata. If disabled, output one record per page.

## `maxPages` (type: `integer`):

Limit pages processed per document. Set 0 to process all pages.

## Actor input object example

```json
{
  "pdfUrls": [],
  "chunkSize": 1800,
  "chunkOverlap": 150,
  "extractTables": true,
  "removeBoilerplate": true,
  "emitChunks": true,
  "maxPages": 0
}
```

# Actor output Schema

## `chunks` (type: `string`):

Dataset of extracted records. In chunk mode each item is {source, section, page\_start, page\_end, chars, text}. In page mode each item is {source, page, columns, markdown, tables\[]}. Failures are {source, error}.

## `chunksCsv` (type: `string`):

Same extracted records in CSV form, for spreadsheet or bulk-import workflows.

## `runInConsole` (type: `string`):

Human-readable view of this run, its log, and its output.

# 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": []
};

// Run the Actor and wait for it to finish
const run = await client.actor("pgrillo/pdf-to-markdown-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 = { "pdfUrls": [] }

# Run the Actor and wait for it to finish
run = client.actor("pgrillo/pdf-to-markdown-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 '{
  "pdfUrls": []
}' |
apify call pgrillo/pdf-to-markdown-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,pgrillo/pdf-to-markdown-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/QhSIZjDziCHancoMs/builds/MvuFlCYLaDbXnRsoM/openapi.json
