# PDF & Document to Markdown Converter for LLM / RAG (`chesapeake/document-to-markdown`) Actor

Convert PDFs, Word (DOCX), PowerPoint (PPTX), Excel (XLSX), HTML, EPUB and scanned images to clean Markdown for ChatGPT, Claude, RAG and vector databases. Tables preserved, automatic OCR for scanned pages, optional chunking. Pay per page.

- **URL**: https://apify.com/chesapeake/document-to-markdown.md
- **Developed by:** [Chesapeake Commerce](https://apify.com/chesapeake) (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 $1.00 / 1,000 page converteds

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 & Document to Markdown Converter for LLM / RAG (OCR, Tables)

Convert **PDF, Word (DOCX), PowerPoint (PPTX), Excel (XLSX/XLS), HTML, EPUB, CSV and scanned images** into clean, structured **Markdown** that's ready for ChatGPT, Claude, Gemini, LangChain, LlamaIndex and vector databases such as Pinecone, Qdrant, Weaviate and pgvector.

Scanned pages are detected automatically and run through **OCR**, while normal pages use the fast text layer. PDF tables become **Markdown tables**. Turn on **RAG chunking** to get heading-aware chunks with overlap. Pricing is **per page** and there's no subscription.

### Why use it

- **Built for LLM pipelines.** You get Markdown, not a messy text dump, plus an approximate token count and optional chunks.
- **Hybrid OCR.** OCR runs only on pages that need it, so mixed scanned and digital PDFs come out right and you only pay the OCR rate for scanned pages.
- **Tables kept** as real `| Markdown | tables |`, with headers.
- **Sideways margin text removed.** Rotated stamps and labels that normally show up as reversed garbage are filtered out.
- **Page markers** (`<!-- page 7 -->`) so your RAG answers can cite page numbers.
- **Bulk.** Thousands of documents per run, with size and page limits that protect your budget.
- **Many formats in one Actor:** PDF, DOCX, PPTX (slides and notes), XLSX/XLS (sheets as tables), HTML, EPUB, CSV, JSON, XML, PNG/JPG/TIFF (multi-page TIFF supported).

### How to use it

1. Add document URLs under **Document URLs**. You can also upload a CSV or text file of URLs. For your own files, upload them to an Apify key-value store, Google Drive (public link) or S3 and paste the links.
2. Leave **OCR** on *Auto*. Set **OCR languages** for non-English scans, e.g. `eng+deu`.
3. Optional: set **RAG chunk size** to something like 1500 to get ready-to-embed chunks.
4. Click **Start** and grab the `markdown` field via API, JSON, CSV or an integration (Make, Zapier, n8n, LangChain `ApifyDatasetLoader`).

#### Input example

```json
{
  "sources": [{ "url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf" }, { "url": "https://arxiv.org/pdf/1706.03762" }],
  "ocrMode": "auto",
  "chunkSize": 1500,
  "chunkOverlap": 200
}
```

#### Output example (shortened)

```json
{
  "url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
  "status": "OK",
  "finalUrl": "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
  "fileName": "fw9.pdf",
  "fileType": "pdf",
  "fileSizeBytes": 140815,
  "pageCount": 6,
  "pagesProcessed": 6,
  "textPages": 6,
  "ocrPages": 0,
  "truncated": false,
  "metadata": {
    "Author": "SE:W:CAR:MP",
    "CreationDate": "D:20240306081813-05'00'",
    "Creator": "Designer 6.5",
    "Keywords": "Fillable",
    "ModDate": "D:20240306081813-05'00'",
    "Producer": "Designer 6.5",
    "Subject": "Request for Taxpayer Identification Number and Certification",
    "Title": "Form W-9 (Rev. March 2024)"
  },
  "markdownChars": 37789,
  "approxTokens": 9447,
  "markdown": "<!-- page 1 -->\n\nW-9\nRequest for Taxpayer\nForm Give form to the\n(Rev. March 2024) Identification Number and Certification requester. Do not\nDepartment of the Treasury send to the IRS.\nGo to www.irs.gov/FormW9 for instructions and the latest information.\nInternal Revenue Service\nBefore you begin. For guidance related to the purpose of Form W-9, see Purpose of Form, below.\n1 Name of entity/individual. An entry is required. (For a sole proprietor or disregarded entity, enter the owner’s name on line 1, and enter the business/disregarded\nentity’s name on line 2.)\n2 Business name/disregarded entity…"
}
```

Fields: `status` (OK / EMPTY / FAILED / HTTP_ERROR / SKIPPED_ROBOTS_TXT), `fileType`, `pageCount`, `textPages`, `ocrPages`, `truncated`, `metadata` (title, author, dates), `markdownChars`, `approxTokens`, `markdown`, and `chunks[]` when chunking is on.

#### LangChain example

```python
from langchain_community.utilities import ApifyWrapper
from langchain_core.documents import Document
loader = ApifyWrapper().call_actor(
    actor_id="chesapeake/document-to-markdown",
    run_input={"sources": [{"url": "https://arxiv.org/pdf/1706.03762"}]},
    dataset_mapping_function=lambda i: Document(page_content=i.get("markdown") or "", metadata={"source": i["url"]}),
)
docs = loader.load()
```

### Pricing (pay per event)

| Event | Price |
|---|---|
| Page converted (text layer) | **$0.001** ($1 per 1,000 pages) |
| Page converted with OCR (scanned page or image) | **$0.006** |
| Actor start | $0.00005 |

**What's a page?** A PDF page, a PPTX slide, an image (or TIFF frame), or, for formats without pages (DOCX, XLSX, HTML, EPUB, CSV), every 3,000 characters of output (minimum 1). Example: 100 digital PDFs of 12 pages = 1,200 pages = **$1.20**. Failed downloads, unsupported files, empty results and robots.txt-blocked URLs are **free**.

### FAQ

**Which PDFs need OCR?** Scans, photographed pages and image-only PDFs. In Auto mode, any page with almost no extractable text gets OCR.

**Does it handle password-protected PDFs?** No. Encrypted PDFs fail and aren't charged.

**How accurate is the OCR?** It uses Tesseract 5. It's excellent on clean scans at 200 DPI and weaker on handwriting or low-quality photos. Math formulas and charts aren't transcribed.

**Can I convert files from my computer?** Yes. Upload them to an Apify key-value store or any file host and pass the URLs. Files are processed in memory and only the Markdown is stored in your run's dataset.

**Is there a size limit?** 50 MB and 300 pages per document by default. Raise **Max file size** and **Max pages** if you need more.

**Do you store my documents?** No. Documents aren't stored; only the Markdown output goes to your own run storage.

# Actor input Schema

## `sources` (type: `array`):

Public links to PDF, DOCX, PPTX, XLSX, HTML, EPUB, CSV or image files (PNG, JPG, TIFF). To convert your own files, upload them to an Apify key-value store or any file host and paste the links.

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

OCR pages are billed at the OCR rate.

## `ocrLanguages` (type: `string`):

Tesseract codes joined by +, e.g. eng+deu. Available: eng, deu, fra, spa, por, ita, nld.

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

Detect PDF tables and output them as | Markdown | tables |.

## `pageMarkers` (type: `boolean`):

Insert  comments between PDF pages (handy for citations).

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

0 = off. Otherwise also return the Markdown split into heading/paragraph-aware chunks of about this size.

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

Characters repeated between consecutive chunks.

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

Longer PDFs are cut off (flagged truncated). Protects your budget.

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

Bigger files are skipped.

## `respectRobotsTxt` (type: `boolean`):

Skip URLs disallowed for automated agents.

## `maxConcurrency` (type: `integer`):

Documents processed in parallel.

## Actor input object example

```json
{
  "sources": [
    {
      "url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
    }
  ],
  "ocrMode": "auto",
  "ocrLanguages": "eng",
  "extractTables": true,
  "pageMarkers": true,
  "chunkSize": 0,
  "chunkOverlap": 200,
  "maxPagesPerDocument": 300,
  "maxFileSizeMb": 50,
  "respectRobotsTxt": true,
  "maxConcurrency": 3
}
```

# Actor output Schema

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

One item per document in the default dataset, including the full Markdown text (and chunks when chunking is enabled).

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

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

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

```

## MCP server setup

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

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/5pv7xjiFjQExvKhRw/builds/E7Sj4AGtD7qi9pFgA/openapi.json
