# PDF to Markdown: PDF & DOCX Document to Markdown for LLM & RAG (`api-co/pdf-to-markdown`) Actor

Convert PDF, DOCX, HTML and text documents to clean Markdown for LLMs and RAG: headings, lists, de-hyphenated text, removed headers/footers, per-page output and token-sized chunks. Bulk PDF to Markdown and PDF to text from URLs.

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

## Pricing

from $0.80 / 1,000 documents

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?

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: PDF & DOCX Document to Markdown for LLM & RAG

Convert **PDF, Word (DOCX), HTML and text files to clean Markdown** for LLMs, RAG pipelines, search indexes and data extraction. Paste URLs (Google Drive, Google Docs, Dropbox and GitHub share links work) and get structured output.

- **Markdown with structure**: headings detected from font sizes and bold lines, bullet and numbered lists, paragraphs re-flowed, words de-hyphenated across line breaks.
- **Clean text**: repeated headers, footers and page numbers are removed automatically.
- **RAG-ready chunks** (optional): split on headings and paragraphs, with the heading path ("Chapter 2 > Results"), source page numbers, token estimates and overlap.
- **Per-page Markdown** (optional) for page-level citations.
- **Metadata**: title, author, subject, keywords, creator/producer, created and modified dates, page count, PDF version, encryption, word count and token estimate.
- **Scanned-PDF detection**: `needsOcr` and `scannedPages` tell you which pages have no text layer, instead of returning silent empty output.
- **Page ranges** (`1-5,8,10-`), **password-protected PDFs**, up to 100 MB per file, and bulk lists.

Text-layer extraction only (no OCR), so it's fast and cheap: a 15-page paper converts in about 0.5 s.

### How to use

1. Paste public URLs of PDF, DOCX, HTML or text files into **URLs**.
2. Optionally turn on *Chunking* to get RAG-ready chunks with token counts, or set a page range.
3. Click **Start** and get clean Markdown (headings, lists, tables) per document.

### Why this Actor

| | This Actor | Typical PDF extractors |
|---|---|---|
| Output | Structured Markdown + chunks + per-page | Raw text blob |
| Headers/footers/page numbers | Removed | Mixed into the text |
| RAG chunks with heading path + pages | **Yes** | Rarely |
| DOCX / HTML / Google Docs | **Yes** | PDF only |
| Price for a 10-page PDF | **$0.005** | $0.01 to $0.03 |

### Input

```json
{ "urls": ["https://arxiv.org/pdf/1706.03762", "https://drive.google.com/file/d/FILE_ID/view"], "chunking": true, "chunkTokens": 800, "includePages": false }
```

### Output

```json
{ "url": "https://arxiv.org/pdf/1706.03762", "fileType": "pdf", "title": "Attention Is All You Need", "totalPages": 15, "pagesProcessed": 15, "wordCount": 6067, "tokensEstimate": 10400,
  "metadata": { "author": null, "created": "2024-04-10T21:11:43Z", "producer": "pdfTeX-1.40.25" }, "needsOcr": false,
  "markdown": "## Attention Is All You Need\n\nAshish Vaswani...\n\nThe dominant sequence transduction models...",
  "chunks": [ { "index": 0, "text": "...", "headingPath": "Attention Is All You Need > 1 Introduction", "pages": [1, 2], "tokens": 790 } ] }
```

### Pricing (pay per event)

- **$0.001 per document** plus **$0.0004 per page** (DOCX/HTML/TXT: 1 page per ~500 words).
- So a 10-page PDF costs **$0.005** and 1,000 ten-page PDFs cost **$5**.
- Failed downloads and unsupported files are free error records. Use *Max pages per document* and the run's max cost to cap spend.

### How much does it cost?

You only pay for results, never for compute time:

| You get | You pay (Starter/Bronze plan price) |
|---|---|
| 100 10-page documents | $0.50 |
| 1,000 10-page documents | $5.00 |
| 10,000 10-page documents | $50.00 |

Apify's **free plan includes $5 of usage every month**, and free-plan users pay **half price** on this Actor, so that covers about **2,000 10-page documents** at no cost. Paid plans get volume discounts (Silver -10%, Gold -20%). Set a *maximum cost per run* and the Actor stops cleanly at your limit.

### Tips

- For scanned PDFs (`needsOcr: true`), run them through an OCR tool first.
- Files behind a login can't be fetched. Upload them to a public location or an Apify key-value store and pass the record URL.

### Run it from code (API, Python, JavaScript)

```bash
curl -X POST "https://api.apify.com/v2/acts/api-co~pdf-to-markdown/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" -d '{"urls": ["https://arxiv.org/pdf/1706.03762"]}'
```

```python
from apify_client import ApifyClient
client = ApifyClient("YOUR_APIFY_TOKEN")
run = client.actor("api-co/pdf-to-markdown").call(run_input={"urls": ["https://arxiv.org/pdf/1706.03762"]})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)
```

```javascript
import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: 'YOUR_APIFY_TOKEN' });
const run = await client.actor('api-co/pdf-to-markdown').call({"urls": ["https://arxiv.org/pdf/1706.03762"]});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
```

It also works from **AI agents through the Apify MCP server**, and with Zapier, Make, n8n, Google Sheets and webhooks. You can schedule it in the Apify Console.

### FAQ

**Does it do OCR on scanned PDFs?**
No. It extracts the text layer of digital PDFs, which covers most reports, papers and invoices generated by software. Scanned or image-only pages are flagged in the output (`needsOcr`, `scannedPages`) so you know which files need an OCR step.

**What formats are supported?**
PDF, DOCX, HTML and plain text, from any public URL, including Google Drive and Dropbox share links.

**Is the output good for RAG?**
Yes. You get Markdown with headings and lists preserved, headers and footers removed, de-hyphenated text, per-page output and ready-made chunks with their heading path and page number.

**How much does it cost?**
About $0.005 for a 10-page PDF. You pay per document and per page converted.

### Use cases

- **RAG and AI agents**: convert manuals, papers and reports into Markdown chunks for a vector database.
- **Document pipelines**: bulk-convert PDFs to text for search, classification or summarization.
- **Research**: extract the text of academic papers and reports.
- **LLM fine-tuning datasets**: clean text with page counts and metadata.

# Actor input Schema

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

Public links to PDF, DOCX, HTML or TXT/MD files. Google Drive, Google Docs, Dropbox and GitHub share links are converted to direct downloads automatically.

## `urlsText` (type: `string`):

Paste many URLs, one per line.

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

Full document as Markdown (headings, lists, paragraphs).

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

Also return plain text without Markdown syntax.

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

Add a 'pages' array with Markdown for each PDF page (for citations and page-level search).

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

Add a 'chunks' array split on headings and paragraphs with heading path, page numbers and token estimates, ready for embeddings.

## `chunkTokens` (type: `integer`):

Target chunk size in tokens (about 4 characters per token).

## `chunkOverlapTokens` (type: `integer`):

Approximate overlap carried between consecutive chunks.

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

PDF pages to convert, e.g. '1-5,8,10-'. Leave empty for all.

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

Safety cap on pages converted (and charged) per PDF.

## `removeHeadersFooters` (type: `boolean`):

Drop running headers, footers and page numbers that repeat across pages.

## `pdfPassword` (type: `string`):

For password-protected PDFs (the same password is tried for every file).

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

Skip files larger than this.

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

Documents converted in parallel.

## `maxItems` (type: `integer`):

Stop after this many documents (defaults to all inputs).

## Actor input object example

```json
{
  "urls": [
    "https://arxiv.org/pdf/1706.03762"
  ],
  "includeMarkdown": true,
  "includeText": false,
  "includePages": false,
  "chunking": false,
  "chunkTokens": 800,
  "chunkOverlapTokens": 100,
  "maxPagesPerDocument": 500,
  "removeHeadersFooters": true,
  "maxFileSizeMb": 100,
  "maxConcurrency": 3
}
```

# Actor output Schema

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

One item per document with Markdown, plain text, metadata and optional RAG chunks.

# 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 = {
    "urls": [
        "https://arxiv.org/pdf/1706.03762"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("api-co/pdf-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 = { "urls": ["https://arxiv.org/pdf/1706.03762"] }

# Run the Actor and wait for it to finish
run = client.actor("api-co/pdf-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 '{
  "urls": [
    "https://arxiv.org/pdf/1706.03762"
  ]
}' |
apify call api-co/pdf-to-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,api-co/pdf-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/ylVQMLa6f3Qpp6TI3/builds/9veSqbDVvOzsIQSUK/openapi.json
