# PDF & Word to Markdown for RAG — Chunks with Page Numbers (`s3nafps/doc-to-markdown`) Actor

Convert PDF and Word (.docx) files from a URL into clean Markdown and RAG-ready chunks, each tagged with its page numbers. No browser, OCR, or paid APIs.

- **URL**: https://apify.com/s3nafps/doc-to-markdown.md
- **Developed by:** [mohamed senator](https://apify.com/s3nafps) (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 $5.00 / 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

## PDF & Word to Markdown for RAG — Chunks with Page Numbers

Turn PDF and Word (.docx) files from a URL into **clean Markdown and RAG-ready chunks**, with PDF chunks tagged with the page numbers they come from. Headings and lists are kept, and Word tables become Markdown tables (PDF tables come out as text rows), so your embeddings and your AI answers can cite the right page. No browser, no OCR, no paid third-party APIs, and you pay per document and per page, not per hour.

### Why use it

- **Clean Markdown**: `#` and `##` headings and lists come out as Markdown, and Word tables become Markdown tables. Repeated running headers and footers are removed.
- **Page numbers on PDF chunks**: each PDF chunk carries `pageStart` and `pageEnd`, so an answer can point to "page 7".
- **Heading-aware chunks**: each chunk keeps its section path (`headingPath`), with a token estimate and overlap between neighbours.
- **Two-column text is read column by column**: when a page is two columns of running text, the left column is read first, then the right. Tables and forms with narrow cells are read row by row.
- **Batch friendly**: convert up to 100 files in one run, one dataset row per converted file (plus failed files when **Save failed files to the dataset** is on).
- **Fair billing**: a failed file costs nothing, a file with no text (a scan) fails and is free, and a scanned page inside a text file is not charged.

### Works with the AI-Ready Webpage Extractor

The chunk format matches the [AI-Ready Webpage Extractor](https://apify.com/s3nafps/ai-ready-webpage-extractor), so web pages and documents can go into the same pipeline. Both return `headingPath`, `content` and `estimatedTokens` for each chunk. This Actor adds `pageStart` and `pageEnd`. Use the Webpage Extractor for HTML pages and this Actor for PDF and Word files.

### How to use it

1. Paste one or more public file URLs in **File URLs**.
2. Leave the defaults, or turn on **Split into RAG chunks** to get chunks.
3. Click **Start** and download the results as JSON, CSV or Excel, or connect them to your pipeline.

#### Example: one PDF

```json
{
  "fileUrls": [{ "url": "https://arxiv.org/pdf/1706.03762" }],
  "outputFormat": "markdown"
}
```

#### Example: a batch of files, chunked for RAG

```json
{
  "fileUrls": [
    { "url": "https://example.com/files/handbook.pdf" },
    { "url": "https://example.com/files/policy.docx" }
  ],
  "chunkContent": true,
  "chunkSizeTokens": 800,
  "chunkOverlapTokens": 100
}
```

### Input

| Field | Description | Default |
| --- | --- | --- |
| `fileUrls` | Public PDF or .docx links (1–100). | required |
| `outputFormat` | `markdown`, `text` or `both`. | `markdown` |
| `chunkContent` | Add a `chunks` array for RAG. | `false` |
| `chunkSizeTokens` | Approximate maximum chunk size, in tokens (minimum 50). | `800` |
| `chunkOverlapTokens` | Text each chunk repeats from the previous one (minimum 0). | `100` |
| `removeHeadersFooters` | Drop running headers and footers in PDFs. | `true` |
| `startPage` | First PDF page to convert. | `1` |
| `maxPagesPerDocument` | Most pages to convert from each PDF (1–5,000). | `500` |
| `maxFileSizeMb` | Largest file to download, in MB (1–200). | `50` |
| `includeFailedDocuments` | Also save a dataset row for each failed file. | `false` |

### Output

One dataset row per converted file. Failed files get a row only when **Save failed files to the dataset** is on (`includeFailedDocuments`), and they are never charged. Example (shortened, with a chunk):

```json
{
  "sourceUrl": "https://example.com/files/handbook.pdf",
  "fileName": "handbook.pdf",
  "fileType": "pdf",
  "title": "Staff Handbook",
  "author": null,
  "createdDate": "2025-03-01T09:00:00.000Z",
  "modifiedDate": null,
  "pageCount": 12,
  "pagesExtracted": 12,
  "markdown": "# Staff Handbook\n\n## Leave policy\n\nEmployees accrue 2 days per month...",
  "text": null,
  "chunks": [
    {
      "index": 0,
      "headingPath": ["Staff Handbook", "Leave policy"],
      "content": "## Leave policy\n\nEmployees accrue 2 days per month...",
      "estimatedTokens": 212,
      "pageStart": 3,
      "pageEnd": 4
    }
  ],
  "wordCount": 5400,
  "estimatedTokens": 7200,
  "scannedPages": [],
  "extractionStatus": "succeeded",
  "errorMessage": null,
  "scrapedAt": "2026-01-20T12:00:00.000Z"
}
```

The dataset has two views: **Overview** (one row per converted file) and **RAG chunks** (one row per chunk, with its page numbers).

A run summary is saved as the `OUTPUT` record in the run's key-value store. It lists how many files succeeded and failed, the reason for each failure, whether the spending limit stopped the run, and `chargeWarnings`: any saved file whose page charge fell short or failed.

### Pricing

Pay per event:

| Event | Price |
| --- | --- |
| Per document converted | $0.005 |
| Per page converted | $0.001 |
| Per run started | $0.00005 |

A Word file has no fixed pages, so it is billed as 500-word pages, with a minimum of one page.

| File | Calculation | Cost |
| --- | --- | --- |
| 10-page PDF | $0.005 + 10 × $0.001 | $0.015 |
| 100-page PDF | $0.005 + 100 × $0.001 | $0.105 |
| 1,200-word Word file (3 pages) | $0.005 + 3 × $0.001 | $0.008 |

- Each run also has a tiny start fee of $0.00005 (a twentieth of a cent), whatever the number of files.
- Failed files are free. A file with no text at all (a scan) fails with a message, so it is free too.
- Scanned pages with no text are free inside a file that has text (they are listed in `scannedPages`).
- Pages before **Start at page** and beyond **Maximum pages per document** are not converted and not charged.
- Your spending limit is respected. Before saving each file, the run checks that the limit covers its fee and page fees, and the default dataset-item event price if you have set one. If it does not, the run stops.
- You are never charged for a document that was not saved, for a failed file, or for an empty page. If a page charge fails after a file is saved, the file stays succeeded, a warning is logged, and the run summary lists it in `chargeWarnings`.

### Use with AI agents (MCP)

Add the Apify MCP server to Claude, Cursor, VS Code or any MCP client, and enable this Actor (`s3nafps/doc-to-markdown`) as a tool. Your agent can then read a PDF or Word file as clean Markdown with page-numbered chunks. See [mcp.apify.com](https://mcp.apify.com).

### Use with the API

```bash
curl -X POST "https://api.apify.com/v2/acts/s3nafps~doc-to-markdown/run-sync-get-dataset-items" \
  -H "Authorization: Bearer YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "fileUrls": [{ "url": "https://arxiv.org/pdf/1706.03762" }], "chunkContent": true }'
```

Or with the JavaScript client:

```js
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('s3nafps/doc-to-markdown').call({
  fileUrls: [{ url: 'https://arxiv.org/pdf/1706.03762' }],
  chunkContent: true,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
```

### Limitations

- **No OCR.** Scanned pages (images of text) have no text to extract. They are listed in `scannedPages` and are not charged. A file with no text at all fails with a message and is not charged.
- **Tables in PDFs come out as text rows**, not as Markdown tables. Each row of a table appears as a line of text.
- **Columns.** Two columns of running text are read column by column. A short full-width line that ends before the right column starts, such as a footer note under two columns, can be read between the two columns. A two-column table with wide cells on both sides may be read column by column, and pages with columns narrower than about a quarter of the page width are read line by line. Pages with three or more columns may also come out mixed.
- **Public URLs only.** The file must be reachable without a login.
- **No password-protected files.** Those fail with a clear message.
- **PDF and Word only.** PowerPoint, Excel and HTML files are not supported.
- **Word files have no page numbers.** Their chunks have `pageStart` and `pageEnd` set to null.
- **Figure pages come out as plain text.** A page with 10 or more rotated text items (typically a chart or diagram) is treated as a figure. Its headings come out as plain text, and chart labels can appear as plain text lines.

### FAQ

**Can I use a Google Drive or Dropbox link?**
Use a direct-download link. For Dropbox, change `?dl=0` at the end of the link to `?dl=1`. A normal Google Drive sharing link returns a web page, not the file, so it will fail. Large Drive files may also show a confirmation page instead of the file.

**Why is a page empty?**
Most likely the page is a scan: an image of text, with no selectable text inside the PDF. This Actor does not run OCR, so the page is listed in `scannedPages` and is not charged. Run the file through an OCR tool first if you need that text.

**How do page numbers work?**
`pageStart` and `pageEnd` are the PDF page numbers, counted from the first page of the file, the same numbers a PDF viewer shows. If you set **Start at page**, numbering still counts from the first page of the file, so the chunks match the viewer. A chunk that spans two pages has both numbers.

**Why does a Word file have no page numbers?**
Word files do not store fixed pages. Their text is converted in full, and only the billing uses 500-word pages.

### Related Actors

- [AI-Ready Webpage Extractor](https://apify.com/s3nafps/ai-ready-webpage-extractor): the same Markdown and chunk format for web pages and whole websites (by links or sitemap), with JavaScript rendering.
- [Webpage to JSON for AI Agents](https://apify.com/s3nafps/webpage-to-json-for-ai-agents): pull specific fields (prices, dates, contacts) from web pages into typed JSON with AI.

### Feedback

Found a file that does not convert well, or need a feature? Open an issue in the **Issues** tab and include the file URL, or a copy of the file if it is public. If the Actor saves you time, a short review on its Store page helps other people find it.

This Actor is intended for public or permitted documents only. Respect copyright and each site's terms of use.

# Actor input Schema

## `fileUrls` (type: `array`):

Public links to the PDF or Word (.docx) files to convert, up to 100 per run.

## `outputFormat` (type: `string`):

Choose whether the text comes back as Markdown (with headings and lists), as plain text, or both.

## `chunkContent` (type: `boolean`):

Turn this on to also get the text split into pieces of similar size, each tagged with its section and, for PDFs, its page numbers, ready for a vector database.

## `chunkSizeTokens` (type: `integer`):

Approximate maximum size of each chunk in tokens (about four characters each), used only when chunking is on.

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

How many tokens each chunk repeats from the end of the previous one, so ideas are not cut off at the boundary (must be smaller than the chunk size).

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

Drop text that repeats at the top or bottom of at least half the pages (and at least three pages), such as running titles and page numbers, so it does not clutter the content.

## `startPage` (type: `integer`):

The first page of each PDF to convert, with earlier pages skipped and not charged.

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

The most pages to convert from each PDF, with later pages skipped and not charged.

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

Files larger than this size in megabytes are reported as failed instead of being converted.

## `includeFailedDocuments` (type: `boolean`):

Turn this on to get a dataset row, with the reason, for each file that could not be converted (failed files are never charged either way).

## Actor input object example

```json
{
  "fileUrls": [
    {
      "url": "https://arxiv.org/pdf/1706.03762"
    }
  ],
  "outputFormat": "markdown",
  "chunkContent": false,
  "chunkSizeTokens": 800,
  "chunkOverlapTokens": 100,
  "removeHeadersFooters": true,
  "startPage": 1,
  "maxPagesPerDocument": 500,
  "maxFileSizeMb": 50,
  "includeFailedDocuments": false
}
```

# Actor output Schema

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

One row per converted file, with its counts and status

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

How many files succeeded and failed, the failure reasons, and whether the spending limit stopped the run

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

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

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

```

## MCP server setup

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