# URL and PDF to Markdown for LLMs and RAG (`magicfingers/document-to-markdown`) Actor

Convert web pages, PDF, Word, PowerPoint and Excel files to clean Markdown for LLMs and RAG: tables kept, headings, metadata, token counts and chunks. OCR for scanned PDFs, Arabic kept in order. Failed sources are free.

- **URL**: https://apify.com/magicfingers/document-to-markdown.md
- **Developed by:** [abdulrahman alrashid](https://apify.com/magicfingers) (community)
- **Categories:** AI, Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.20 / 1,000 url converteds

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

## URL and PDF to Markdown for LLMs and RAG

Turn web pages, PDF, Word, PowerPoint and Excel files into clean Markdown that an LLM can read: tables stay tables, headings and lists stay in place, and every result comes with its title, author, date, language and token count. Add token-sized chunks for your vector store with one setting. You pay only for sources that were converted; failed links and files are free, and the 5 USD of free monthly credit covers about 3,333 web pages or short documents.

### What is URL and PDF to Markdown?

URL and PDF to Markdown is a document parser API on Apify. Give it links, upload files or point it at the URL field of any dataset, and it saves one row per source with the content as Markdown. It is built for RAG pipelines, AI agents and knowledge-base imports, where clean text means fewer tokens and fewer errors downstream.

- Web pages and documents in one Actor and one output format.
- Tables kept as Markdown tables in every format, with the table count in each row.
- Arabic and other right-to-left text kept in logical order, also inside PDF tables.
- Optional chunks of a chosen token size, cut at headings first, with overlap and the page each chunk starts on.
- Two document modes: fast (text layer) and accurate (layout model, complex tables, OCR for scanned pages).
- Optional JSON structure of every heading, paragraph, list item and table with its page number.

### What can it convert?

| Source | How it is read | Notes |
|---|---|---|
| Web pages (HTML) | Main content found with trafilatura (menus, footers and banners removed); headings, lists, tables and code kept | A headless browser opens pages that need JavaScript (`renderJs`) |
| PDF, fast mode | Text layer read with PDFium (pypdfium2): rows, aligned columns become tables, two-column pages read column by column, repeated headers, footers and page numbers removed | Scanned pages have no text layer: they are skipped and listed in `warnings` |
| PDF, accurate mode | Docling layout model and TableFormer table model on CPU, Tesseract OCR in English and Arabic for pages without a text layer | Slower, priced per page |
| Word (.docx) | python-docx: headings, numbered and bullet lists, tables (merged cells kept in place), content controls, text boxes, links | Pages are the count Word saved in the file |
| PowerPoint (.pptx) | python-pptx: one section per slide with its title, text in reading order, tables, speaker notes | Pages are slides |
| Excel (.xlsx) | openpyxl: one Markdown table per sheet with cached formula values, up to 500 rows per sheet | Pages are sheets |

The type is read from the file's own bytes, not from its name or the server's Content-Type, so a PDF served as `application/octet-stream` or a link without an extension still works. Older binary formats (.doc, .xls, .ppt), macro-enabled files (.docm, .xlsm, .pptm), images, CSV and plain text are not converted; such sources are listed in `FAILED` with the reason.

### How to convert a PDF or web page to Markdown

1. Paste links into **URLs of pages and documents**, upload files in **Upload documents**, or choose a dataset in **Dataset with URLs** and name the field with the links.
2. Pick the **Document mode** (fast or accurate) and, for RAG, a **Chunk size** in tokens.
3. Click **Start**, then open the **Output** tab: the **Overview** view lists every source with its type, title and tokens, **Markdown** shows the text and **Chunks** lists one line per chunk. Export to JSON, CSV or Excel, or read the dataset with the Apify API.

### How much does it cost?

You pay per converted web page or document, plus a small fee per page for long documents. Failed links, blocked addresses, unsupported, damaged or password-protected files, and documents without text cost nothing.

| Event | Charged when | Free plan | Bronze | Silver | Gold |
|---|---|---|---|---|---|
| URL converted (`url-converted`) | One web page or document converted and its row saved. Failed sources are not charged. | 1.50 USD per 1,000 events | 1.50 USD per 1,000 events | 1.35 USD per 1,000 events | 1.20 USD per 1,000 events |
| Actor start (`apify-actor-start`) | Charged by Apify when the run starts: once up to 1 GB of memory, then once for each extra GB. | 0.05 USD per 1,000 runs | 0.05 USD per 1,000 runs | 0.05 USD per 1,000 runs | 0.05 USD per 1,000 runs |
| Extra page (`extra-page`) | Fast mode: each document page beyond the first 5 (PDF pages, slides, sheets, Word pages). | 0.50 USD per 1,000 events | 0.50 USD per 1,000 events | 0.45 USD per 1,000 events | 0.40 USD per 1,000 events |
| Accurate page (`accurate-page`) | Accurate mode: each PDF page converted with the layout model and OCR. | 4.00 USD per 1,000 events | 4.00 USD per 1,000 events | 3.60 USD per 1,000 events | 3.20 USD per 1,000 events |

Example: 1,000 web pages or documents on the Bronze plan cost 1,000 x 0.0015 USD = 1.50 USD, plus 0.00005 USD for the run start. Platform usage (compute, storage, traffic) is included in these prices.

Free plan: the 5 USD of monthly Apify credit covers about 3,333 web pages or documents a month when no other Actor is used.

Worked examples on the Bronze plan:

- Web pages: 1,000 pages cost 1,000 x 0.0015 USD = 1.50 USD.
- Documents in fast mode: a 10-page PDF costs 0.0015 USD plus 5 x 0.0005 USD for pages 6 to 10, so 0.004 USD; 1,000 of them cost 4.00 USD.
- Accurate mode: a 20-page PDF costs 0.0015 USD plus 20 x 0.004 USD, so 0.0815 USD.

Only converted pages are charged: pages left out by **Pages to convert** or cut by **Max pages per document** cost nothing. Set a maximum cost per run in the run options: the Actor counts a document's pages before converting it, converts only the pages that fit (with a warning in the row), and then starts no new source.

### Input example

```json
{
    "urls": [
        "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
        "https://example.com"
    ],
    "documentMode": "fast",
    "chunkTokens": 500,
    "chunkOverlap": 100,
    "pageRange": "1-20",
    "includeLinks": false
}
```

A crawler's dataset as input, with the links in `page.url`:

```json
{
    "datasetId": "YOUR_DATASET_ID",
    "urlField": "page.url",
    "renderJs": "never",
    "chunkTokens": 800
}
```

### Output example with chunks

A row from a real run of the dummy PDF above in accurate mode with a chunk size of 100 tokens:

```json
{
    "url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
    "finalUrl": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
    "source": "urls",
    "sourceType": "pdf",
    "mode": "accurate",
    "title": null,
    "language": null,
    "author": "Evangelos Vlachogiannis",
    "publishedAt": "2007-02-23T17:56:37+02:00",
    "pages": 1,
    "pageCount": 1,
    "markdown": "## Dummy PDF file\n",
    "markdownTruncated": false,
    "markdownUrl": null,
    "fullResultUrl": null,
    "tokenCount": 5,
    "chunks": [
        {"index": 0, "text": "## Dummy PDF file", "tokenCount": 4, "startPage": 1}
    ],
    "structure": null,
    "tablesCount": 0,
    "ocrPages": 0,
    "renderedWithBrowser": false,
    "warnings": [],
    "bytes": 13264,
    "convertedAt": "2026-11-12T23:36:16Z"
}
```

The run's key-value store also holds:

- `OUTPUT`: counts of converted, failed and skipped sources, why the run stopped (if it stopped early) and the events charged.
- `FAILED`: each source that gave no result, with the reason (for example `HTTP 404`, `password-protected PDF`, `no text: the selected pages are scanned images`, `blocked: 10.0.0.1 is a private or reserved address`) and the number of attempts.
- Texts above 2 MB: the whole Markdown as a `.md` record (linked by `markdownUrl`) and, with chunks or structure, a `.json` record (linked by `fullResultUrl`); the row keeps the first 100,000 characters.

### Output fields

| Field | Type | Description |
|---|---|---|
| `url` | string | The source as requested: a web page or document link, or the link of an uploaded file. |
| `finalUrl` | string | The address that answered, after all redirects (for uploaded files: the record link). |
| `source` | string | Where the source came from: urls, files or dataset. |
| `sourceType` | string | Type read from the file's bytes, not from its name: html, pdf, docx, pptx or xlsx. |
| `mode` | string | How it was converted: fast, or accurate (PDFs in accurate mode only). |
| `title` | string or null | Title from the page or document metadata, or from the main heading of a web page. |
| `language` | string or null | Language as declared by the page (html lang) or document properties; null when not declared. |
| `author` | string or null | Author from the page or document metadata, when present. |
| `publishedAt` | string or null | Date from the page or document metadata (ISO 8601); for documents the creation date. |
| `pages` | integer or null | Documents only: pages (PDF), slides (PPTX), sheets (XLSX) or saved or estimated pages (DOCX) converted and charged. Null for web pages. |
| `pageCount` | integer or null | Documents only: all pages, slides or sheets in the file, also those not converted. |
| `markdown` | string | The content as Markdown: headings, paragraphs, lists and tables. Cut to the first 100,000 characters when the text is above 2 MB (see markdownUrl). |
| `markdownTruncated` | boolean | True when markdown holds only the start of the text; the whole text is at markdownUrl. |
| `markdownUrl` | string or null | Link to the whole Markdown in the run's key-value store, when the text is above 2 MB; null otherwise. |
| `fullResultUrl` | string or null | Link to a JSON record with the whole Markdown, chunks and structure, when they were too large for the row; null otherwise. |
| `tokenCount` | integer | Tokens in the whole Markdown, counted with the cl100k_base tokenizer. |
| `chunks` | array or null | Chunks for RAG when chunkTokens is above 0: index, text, tokenCount and startPage (page of the chunk's first text; null for web pages). Null otherwise. |
| `structure` | array or null | When includeStructure is on: every block in order with its type (heading, paragraph, list, table, code, quote), text, level, page and, for tables, rows of cells. Null otherwise. |
| `tablesCount` | integer | Tables found and kept as Markdown tables. |
| `ocrPages` | integer | Pages without a text layer read with OCR (accurate mode only). |
| `renderedWithBrowser` | boolean | True when the page was opened in a headless browser to run its JavaScript. |
| `warnings` | array | Notes about this source, for example scanned pages skipped in fast mode, pages cut by maxPagesPerDocument, or sheets cut at 500 rows. |
| `bytes` | integer | Size of the downloaded file or page in bytes. |
| `convertedAt` | string | Time the source was converted (ISO 8601, UTC). |

### Fast versus accurate mode

| | Fast | Accurate |
|---|---|---|
| PDF text | Text layer (PDFium) | Layout model (Docling) |
| Tables | Simple tables: one line per row, columns that line up | Complex tables, merged cells, cells over several lines |
| Multi-column pages | Two columns detected | Any reading order the layout model finds |
| Scanned pages | Skipped, listed in `warnings` | OCR in English and Arabic (Tesseract) |
| Speed (one core) | About 0.01 s per page | About 4.3 s per page |
| Price per page | Pages beyond 5: 0.50 USD per 1,000 | Every page: 4.00 USD per 1,000 |
| Memory | Default 2,048 MB is plenty | At least 3,072 MB; 4,096 MB recommended |

Accurate mode applies to PDFs. Word, PowerPoint, Excel and web pages already carry their structure, so they are always converted the fast way and priced as fast documents, also in accurate mode.

### Use in RAG pipelines, n8n, Make and MCP clients

- RAG: set **Chunk size** (for example 500 tokens with 100 tokens of overlap) and load the `chunks` of each row into your vector store; `startPage` and `url` give the citation for each chunk. Token counts use the cl100k_base tokenizer.
- n8n and Make: call the Actor with the Apify node or module, then read the dataset items of the run. Schedule a saved task to convert a document folder or a sitemap's pages every day.
- After a crawler: set **Dataset with URLs** to the crawler's dataset, or add this Actor as an integration that starts when the crawler's run finishes.
- AI agents and MCP clients: add the Actor as a tool in Apify's MCP server, give it a URL and read back the Markdown.

### Limits

- No log-in or paywalled pages: a page shows what an anonymous visitor sees. The Actor does not solve captchas or pass bot protection, and it sends an honest user agent.
- Fast mode reads only the text layer: scanned pages are skipped, and complex PDF layouts (tables with cells over several lines, three or more text columns, text inside images) can still merge or split cells. Use accurate mode for those.
- Accurate mode is slower and needs more memory: about 4.3 seconds per page on one core (measured), and about 1,600 MB for the models and the pages in progress (pages are converted 8 at a time to keep memory flat). It refuses to start below 3,072 MB of memory; use 4,096 MB. Apify gives one CPU core per 4,096 MB, so more memory also means more speed.
- OCR quality depends on the scan: short words in table cells of scanned Arabic pages can be misread, and scanned pages are read in English and Arabic only.
- One document may take at most 120 seconds plus half a second per page in fast mode, and 90 seconds plus 30 seconds per page in accurate mode; a document that takes longer or needs more memory than the run allows is listed in `FAILED`.
- Files above **Max file size** (50 MB by default, at most 200 MB) and web pages above 10 MB are skipped. Up to 10,000 sources per run.
- Excel sheets are cut at 500 rows below the header row and 200 columns. Images, charts and embedded files inside documents are not described.
- Password-protected, damaged, empty and legacy-format files fail with a clear reason and are not charged. Files with entity declarations in their XML or extreme compression ratios are refused as unsafe.
- Word files have no fixed pages: **Pages to convert** does not apply to them, and their page count is the one Word saved (or one page per 3,000 characters when none was saved).
- Only public `http` and `https` addresses are fetched. Private, loopback and link-local addresses are refused before every request and every redirect, the browser's requests included.
- Language is the one the page or document declares; it is not guessed from the text.

### Libraries and licences

Each type is converted by open-source libraries with licences that allow commercial use: trafilatura (Apache-2.0), lxml (BSD-3-Clause), pypdfium2 and PDFium (Apache-2.0 and BSD-3-Clause), python-docx, python-pptx and openpyxl (MIT), Docling (MIT) with its layout model (Apache-2.0) and TableFormer model (CDLA-Permissive-2.0), PyTorch (BSD-3-Clause), OpenCV (Apache-2.0), Tesseract and its language data (Apache-2.0), tiktoken (MIT), Playwright (Apache-2.0) and Chromium (BSD-3-Clause and others). The full list with versions is in `NOTICE.md`.

### FAQ

**Am I charged for failed links?** No. A source is charged only after its row is saved. Links that fail, blocked addresses, unsupported or damaged files and documents without text are listed in `FAILED` and are free.

**Why is a PDF table split into odd rows in fast mode?** Fast mode reads the text layer line by line, so a cell with two lines of text becomes two rows. Run the document in accurate mode, where the table model rebuilds the cells.

**Does it keep Arabic in the right order?** Yes. Text is returned in logical (reading) order, shaped letters are turned back into plain letters, and the first column of a right-to-left table is the rightmost one. Accurate mode reads scanned Arabic pages with OCR.

**Can it read only some pages?** Yes. Set **Pages to convert**, for example `1-10, 15`, for PDF pages, PowerPoint slides and Excel sheets. Only converted pages are charged.

**What happens with very long documents?** They stop at **Max pages per document** (200 by default) with a warning. Texts above 2 MB are saved whole in the key-value store and linked from the row.

**Are my files safe?** Each file is parsed in a separate process with time and memory limits and without access to your Apify token; macros and embedded content are never run. Files stay in your own run storage.

### Other Actors by the same author

- [Bulk File and Image Downloader](https://apify.com/magicfingers/bulk-file-downloader): file and image URLs to stored files with links and ZIP parts.
- [Tech Stack Detector](https://apify.com/magicfingers/techstack-detector): the CMS, shop platform, analytics and hosting of a list of websites.
- All Actors: [apify.com/magicfingers](https://apify.com/magicfingers)

# Changelog

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

# Actor input Schema

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

Web pages or direct links to documents, one per line (count: up to 10,000 sources per run, together with files and the dataset). Supported: HTML pages, PDF, Word (.docx), PowerPoint (.pptx) and Excel (.xlsx). Only public http and https links; pages behind a log-in show only what a visitor sees.

## `files` (type: `array`):

Optional: upload PDF, DOCX, PPTX, XLSX or HTML files (or give links to files). Uploaded files are stored in a key-value store of your choice and read from there by this run.

## `datasetId` (type: `string`):

Optional: also read URLs from this dataset (ID or name), for example the output of a crawler run. The Actor only reads it, 1,000 rows at a time.

## `urlField` (type: `string`):

Field of each dataset row that holds the URL, as a dot path such as url or page.url (text: a field name). Arrays are expanded, so a list of links gives one source per link.

## `documentMode` (type: `string`):

fast: the PDF text layer and simple tables, no OCR (scanned pages are skipped and listed in warnings). accurate: a layout model for complex tables and multi-column pages, plus OCR in English and Arabic for scanned pages; slower and priced per PDF page. Word, PowerPoint, Excel and HTML are always converted the fast way.

## `renderJs` (type: `string`):

Open web pages in a headless browser. auto: only when the plain HTML has almost no text (under 200 characters), for example single-page apps. never: plain HTML only (fastest). always: every web page in the browser.

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

Keep links in the Markdown as [text](url). Off: link text only, which saves tokens.

## `includeStructure` (type: `boolean`):

Add a structure array to each row: every heading, paragraph, list item, table (with its cells) and code block in order, with its page number.

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

Optional pages of PDFs, slides of PowerPoint files and sheets of Excel files to convert (text: pages and ranges such as 1-5, 8, 10-). Empty: all pages. Word files have no fixed pages and are always converted whole.

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

Stop a document after this many pages (unit: pages, slides or sheets). The row then has a warning. Word files are cut at the same share of their text.

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

Split each result into chunks of about this many tokens (cl100k_base tokenizer), cut at headings first, then paragraphs, then sentences. 0: no chunks. Otherwise at least 50 (unit: tokens).

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

Tokens repeated from the end of one chunk at the start of the next (unit: tokens). At most half of the chunk size is used.

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

Skip files larger than this (unit: MB, 1 MB = 1,048,576 bytes). The download stops as soon as a file passes the limit. Web pages are limited to 10 MB.

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

Sources downloaded and converted at the same time (unit: sources). Conversions also share the run's memory: the Actor runs one converter process per GB.

## Actor input object example

```json
{
  "urls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
    "https://example.com"
  ],
  "urlField": "url",
  "documentMode": "fast",
  "renderJs": "auto",
  "includeLinks": false,
  "includeStructure": false,
  "maxPagesPerDocument": 200,
  "chunkTokens": 0,
  "chunkOverlap": 100,
  "maxFileSizeMb": 50,
  "maxConcurrency": 5
}
```

# Actor output Schema

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

One row per converted source: Markdown, metadata, token count and optional chunks, as JSON.

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

Keys of the run's key-value store: full Markdown (.md) and full results (.json) of texts above 2 MB.

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

Counts of converted, failed and skipped sources, the reason the run stopped and the events charged.

## `failed` (type: `string`):

Sources that gave no result, with the reason and the number of attempts. They are not charged.

# 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://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
        "https://example.com"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("magicfingers/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 = { "urls": [
        "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
        "https://example.com",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("magicfingers/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 '{
  "urls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
    "https://example.com"
  ]
}' |
apify call magicfingers/document-to-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,magicfingers/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/4m7ua7yxhop2njmq2/builds/aHHuh3Ua825dWHyvl/openapi.json
