# Document to Markdown for AI: PDF, DOCX, HTML to RAG chunks (`opstoolkit/document-to-markdown-rag`) Actor

Give it links to PDF, Word, HTML or text files, get clean markdown plus overlapping chunks with page numbers for RAG and embeddings. Keeps headings and tables. No outside APIs. $1.50 per 1,000 documents, PDF pages after 5 are $0.20 per 1,000.

- **URL**: https://apify.com/opstoolkit/document-to-markdown-rag.md
- **Developed by:** [Elio Saliba](https://apify.com/opstoolkit) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.50 / 1,000 document 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

## Document to Markdown for AI: PDF, DOCX, HTML to RAG chunks

Give it links to PDF, Word, HTML, Markdown or text files and get clean markdown with headings, lists and tables kept, plus overlapping chunks sized for embeddings. For PDFs, every chunk carries its page numbers, so an answer can cite "page 14".

Built for teams loading contracts, manuals, reports and policies into a vector database or a chatbot.

**$1.50 per 1,000 documents**, and $0.20 per 1,000 pages after the first 5 pages of each PDF. Chunking is included. No outside APIs and no per-token fees. Apify's free monthly credit covers a first test at no cost.

### What you get

One dataset row per document (or one row per chunk, your choice), plus a `SUMMARY` record that lists any file that failed and why.

| Field | Example | What it is for |
|---|---|---|
| `markdown` | `# Your Rights\n\n## as a Taxpayer ...` | The whole document as markdown |
| `chunks` | 8 chunks of about 400 tokens | Ready for embeddings, each with `headingPath` and `pageStart` / `pageEnd` |
| `title`, `author`, `createdAt` | `Publication 1 (Rev. 9-2017)` | From the file's own properties, or the first heading |
| `pageCount`, `pagesConverted` | `2`, `2` | For PDFs |
| `wordCount`, `tokenEstimate` | `1894`, `2836` | Plan your embedding budget before you embed |
| `contentHash` | `1416d0a6...` | Spot a changed file between runs |
| `warnings` | `["only the first 200 of 340 pages were converted"]` | Anything you should know about this file |

### How to use

1. **Paste the links** to your files. Each link must open without a login. A file you uploaded to an Apify key-value store works, if its link is public.
2. **Pick the chunk size.** 512 tokens suits most embedding models. Set 0 if you only want the markdown.
3. **Press Start.** Open the dataset, or call the API from your pipeline.

For a vector database, set **Dataset rows** to "One row per chunk". Each row is flat: `chunkId`, `fileName`, `headingPath`, `pageStart`, `pageEnd`, `text`.

### Use it from an AI agent

In Claude, ChatGPT or Cursor, add the Apify MCP server (https://mcp.apify.com) and ask in plain words. The agent finds this Actor (`opstoolkit/document-to-markdown-rag`), fills in the input from your sentence, runs it and reads the result back.

Example prompt: "Convert https://example.com/handbook.pdf and https://example.com/policy.pdf into markdown chunks with page numbers, one row per chunk."

The agent gets flat rows with `chunkId`, `fileName`, `headingPath`, `pageStart`, `pageEnd` and `text`, or one row per document with `markdown`. A `SUMMARY` record says why any file failed.

### Input example

```json
{
  "documentUrls": [
    { "url": "https://www.irs.gov/pub/irs-pdf/p1.pdf" },
    { "url": "https://example.com/handbook.docx" }
  ],
  "chunkSize": 512,
  "chunkOverlap": 64,
  "outputMode": "documents",
  "maxPagesPerDocument": 200,
  "extractTables": true
}
```

- **Chunk size** is in estimated tokens (about 4 characters each, one per CJK character). Paragraphs, lists, code blocks and tables stay whole when they fit. A heading never ends a chunk.
- **Chunk overlap** repeats the end of the previous chunk, so a sentence keeps its context.
- **Put the heading path at the top of each chunk** adds `Title > Section > Subsection` before the text. It often improves retrieval for short chunks.
- **PDF password** is used for every protected PDF in the list. The value is stored as a secret.
- **Max file size** (25 MB by default, 100 MB at most) and **time limit per document** protect your run. A file over either limit is skipped, not charged, and listed in `SUMMARY`.

### Output example

From a real run on a public document, the IRS Publication 1 (shortened):

```json
{
  "url": "https://www.irs.gov/pub/irs-pdf/p1.pdf",
  "fileName": "p1.pdf",
  "fileType": "pdf",
  "sizeBytes": 324302,
  "title": "Publication 1  (Rev. 9-2017)",
  "createdAt": "2017-10-31",
  "pageCount": 2,
  "pagesConverted": 2,
  "wordCount": 1894,
  "tokenEstimate": 2836,
  "headings": ["Your Rights", "as a Taxpayer", "The Taxpayer Bill of Rights"],
  "warnings": [],
  "markdown": "# Your Rights\n\n## as a Taxpayer\n\nThe IRS Mission\n\n### The Taxpayer Bill of Rights\n\nPublication 1\n\nThis publication explains your rights as a taxpayer ...",
  "chunkCount": 8,
  "chunks": [
    {
      "chunkId": "d7760c41d5-1",
      "index": 1,
      "tokenEstimate": 416,
      "headingPath": ["Your Rights", "as a Taxpayer", "The Taxpayer Bill of Rights"],
      "pageStart": 1,
      "pageEnd": 1,
      "text": "5. The Right to Appeal an IRS Decision in an Independent Forum\n\nTaxpayers are entitled to a fair and impartial administrative appeal of most IRS decisions ..."
    }
  ]
}
```

A 38-page PDF (IRS Publication 3, with tables) converted into 108 chunks in about 6 seconds on 1 GB. The start of a table from that file came out like this:

```
| A | Uncollected social security or RRTA tax on tips | B | Uncollected Medicare tax on tips (but not Additional Medicare Tax) | C | Taxable cost of group-term life insurance over $50,000 |
| --- | --- | --- | --- | --- | --- |
| D | Elective deferrals to a section 401(k) cash or deferred arrangement plan (including a SIMPLE 401(k) arrangement) | E | Elective deferrals under a section 403(b) salary reduction agreement | F | Elective deferrals under a section 408(k)(6) salary reduction SEP (this includes elective deferrals made to a Roth SEP IRA) |
```

The first row of a table becomes its header row, whether or not the file marks it as one.

### What it reads

| File | How it is converted |
|---|---|
| PDF | Headings from font size, bullet and numbered lists, tables drawn with ruling lines, text columns in reading order, hyphenated line breaks joined, page headers, footers and page numbers removed |
| DOCX | Heading and Title styles, bullet and numbered lists with levels, bold and italic, links, tables, document properties |
| HTML | The same main-content extraction as the companion Actor: menus, footers and banners removed |
| Markdown, TXT | Passed through, with hard-wrapped lines joined into paragraphs |

The file type is detected from the file's contents, not its name, so a PDF served with the wrong extension still works.

### Use cases

- **Contract and policy search**: chunks with page numbers, so a reviewer can jump to the page.
- **Internal knowledge bases**: a folder of handbooks and SOPs turned into one clean dataset.
- **Report archives**: read thousands of quarterly PDFs into a searchable index.
- **Pairing with a site crawl**: the companion Actor, [Website to Markdown for AI](https://apify.com/opstoolkit/website-to-markdown-rag), lists the PDF and Word links it finds. Pass them here.

### Pricing

Pay per event, two events:

- **$1.50 per 1,000 documents converted** ($0.0015 each). It covers the first 5 pages of a PDF, and the whole of any DOCX, HTML, Markdown or text file.
- **$0.20 per 1,000 PDF pages** ($0.0002 each) for every PDF page after the first 5.

Apify adds a small fee for each run start.

| What you convert | Cost |
|---|---|
| 100 Word files or short PDFs | $0.15 |
| 100 PDFs of 20 pages each | $0.45 |
| One 300-page PDF | about $0.06 |
| 1,000 PDFs of 10 pages each | $2.50 |

Files that fail, time out, are too large or have no text are free. Pages beyond **Max pages per PDF** are not converted and not charged.

**Compared with other options.** Other PDF-to-markdown Actors on the Store charge about $0.003 per file plus $0.0003 to $0.0005 per page, and several add a separate fee for OCR. This one costs half of that per file and 33 to 60 percent less per page. It does not do OCR (see Limits).

### Limits

- **No OCR.** A scanned PDF with no text layer is reported as a failure with a clear message and is not charged. A PDF with some scanned pages gets a warning.
- Word `.docx` only. Old `.doc`, PowerPoint and Excel files are refused with a message. Save them as `.docx` or PDF first.
- Headings in PDFs come from font size. A PDF that uses one font size for everything has few headings. Bold short lines are used as a fallback.
- Only tables drawn with ruling lines are detected. A table made of aligned spaces comes out as text.
- Reading order follows the order the PDF stores its text in. Two-column papers read correctly; unusual layouts such as magazines may not. Right-to-left text depends on how the PDF stores it.
- If a PDF does not map its ligatures to text, a letter pair such as "fi" can drop out ("Of ce"). That is the file, not the conversion.
- Up to 2,000 documents per run, 100 MB per file and 2,000 pages per PDF.
- Big PDFs need memory. The default of 1 GB suits files up to about 50 MB.

### Using the output

**LangChain, from the chunk rows:**

```python
from apify_client import ApifyClient
from langchain_core.documents import Document

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("opstoolkit/document-to-markdown-rag").call(run_input={
    "documentUrls": [{"url": "https://example.com/handbook.pdf"}],
    "outputMode": "chunks",
})
docs = [
    Document(page_content=row["text"],
             metadata={"source": row["url"], "title": row["title"], "page": row.get("pageStart"),
                       "section": " > ".join(row["headingPath"])})
    for row in client.dataset(run["defaultDatasetId"]).iterate_items()
]
```

**LlamaIndex:**

```python
from llama_index.core import Document, VectorStoreIndex

nodes = [Document(text=row["text"], metadata={"file": row["fileName"], "page": row.get("pageStart")})
         for row in client.dataset(run["defaultDatasetId"]).iterate_items()]
index = VectorStoreIndex.from_documents(nodes)
```

Everything Apify supports works here: schedules, webhooks, the REST API, and the integrations with Zapier, Make, n8n, Pinecone, Qdrant and others. The **API** tab has ready code for JavaScript, Python and cURL.

### Works well with

- **[Website to Markdown for AI](https://apify.com/opstoolkit/website-to-markdown-rag)**: crawls a site and lists the PDF and Word links it finds in `SUMMARY.documentLinks`. Pass them here to bring the files in next to the pages.
- **[Image and Scanned PDF OCR](https://apify.com/opstoolkit/image-pdf-ocr)**: this Actor does no OCR. A scanned PDF with no text layer fails here, free, with a clear message. Run those files through OCR instead.
- **[AI Structured Extractor](https://apify.com/opstoolkit/ai-structured-extractor)**: to pull fields such as parties, dates or amounts out of contracts and reports, give it this run's dataset with `datasetId` and `field` set to `markdown` (use **One row per document**). Raise its page size limit for long files.
- **[Dataset Cleaner](https://apify.com/opstoolkit/dataset-cleaner)**: removes duplicate records and normalizes dates, phones and country names in whatever the extractor returns.

A typical chain: Website to Markdown finds the file links, this Actor converts them, AI Structured Extractor reads the fields, Dataset Cleaner tidies the table.

### FAQ

**My files are on my computer. How do I use this?**
Upload them to an Apify key-value store, or to any storage that gives a public link, and paste the links. The Actor only downloads files over http and https.

**Why did a file fail?**
Open `SUMMARY`. Each failed file has a plain reason: the link needs a login, the PDF is scanned, the file is over the size limit, and so on.

**Is my data sent to an AI service?**
No. The conversion runs inside the Actor, with no calls to outside APIs.

**Can it read a password-protected PDF?**
Yes, if you give the password in "PDF password". One password applies to every PDF in the list.

**Something broke.**
Open an issue on the Issues tab with the run link. I reply within a day.

# Changelog

This Actor's version history is a separate document: https://apify.com/opstoolkit/document-to-markdown-rag/changelog.md

# Actor input Schema

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

Public links to the files to convert. Accepts PDF, DOCX, HTML, Markdown and plain text. Example: https://example.com/handbook.pdf. The link must open without a login. A file uploaded to an Apify key-value store works when its link is public. Local file paths are not accepted. Up to 2,000 documents.

## `maxDocuments` (type: `integer`):

Most documents to convert from the list, from 1 to 2,000. Default 100. You pay per document converted.

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

Target size of each chunk in estimated tokens (about 4 characters each), from 0 to 8,000. Default 512, which suits most embedding models. 0 skips chunking and returns markdown only.

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

Tokens repeated from the end of the previous chunk, so a sentence keeps its context. Default 64, from 0 to 4,000. It must not be more than half of the chunk size, or the run stops with an input error.

## `prependHeadingsToChunks` (type: `boolean`):

When on, each chunk's text starts with its heading path (title > section > subsection). This helps retrieval when a chunk is read alone. Default off, so the text stays exactly as in the file.

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

What one dataset row is. 'documents' (default): one row per document with its markdown and chunks inside. 'chunks': one flat row per chunk (chunkId, fileName, headingPath, pageStart, pageEnd, text), ready for a vector database. The price is per document either way.

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

Most pages to convert from one PDF, from 1 to 2,000. Default 200. Pages after the limit are not converted and not charged. The first 5 pages of each PDF are in the document price; each page after that is charged.

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

When on (default), tables drawn with ruling lines in PDFs become markdown tables. Tables without lines are read as plain text.

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

Password for protected PDFs. One password is used for every protected PDF in the list. Leave empty when no PDF is protected. Stored as a secret.

## `includeLinks` (type: `boolean`):

When on (default), hyperlinks in HTML files stay as markdown links. Turn it off for plain text without URLs. Applies to HTML files.

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

Largest file to accept, in megabytes, from 1 to 100. Default 25. Larger files are skipped with a message and not charged. For PDFs over 50 MB, raise the run memory to 2048 MB or more.

## `timeoutPerDocumentSecs` (type: `integer`):

Seconds allowed for one document, from 10 to 900. Default 120. A document that takes longer is skipped and not charged.

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

How many files are downloaded and converted at the same time, from 1 to 10. Default 3.

## Actor input object example

```json
{
  "documentUrls": [
    {
      "url": "https://www.irs.gov/pub/irs-pdf/p1.pdf"
    }
  ],
  "maxDocuments": 100,
  "chunkSize": 512,
  "chunkOverlap": 64,
  "prependHeadingsToChunks": false,
  "outputMode": "documents",
  "maxPagesPerDocument": 200,
  "extractTables": true,
  "includeLinks": true,
  "maxFileSizeMb": 25,
  "timeoutPerDocumentSecs": 120,
  "maxConcurrency": 3
}
```

# Actor output Schema

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

No description

## `summary` (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": [
        {
            "url": "https://www.irs.gov/pub/irs-pdf/p1.pdf"
        }
    ]
};

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

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

```

## MCP server setup

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

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/6Fh10hm4w2kWaUYyq/builds/u0xvDRGrh5RpkocfP/openapi.json
