# PDF & DOCX to Markdown + JSON Chunks for RAG (`badboxx_newlife/pdf-docx-to-markdown-chunks`) Actor

- **URL**: https://apify.com/badboxx_newlife/pdf-docx-to-markdown-chunks.md
- **Developed by:** [Francesco Correnti](https://apify.com/badboxx_newlife) (community)
- **Stats:** 2 total users, 1 monthly users, 90.9% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$20.00 / 1,000 pages

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 to Markdown & DOCX to Markdown + RAG Chunks for LLM Ingestion

Turn PDF and DOCX files into clean Markdown and heading-aware JSON chunks, ready for a vector database. Built for **pdf to markdown** and **docx to markdown** conversion, **rag chunks** generation and **llm ingestion** pipelines: smart **chunking** that follows your headings, with token counts and page numbers, ready to embed and load into any **vector database**.

Keywords: pdf to markdown, docx to markdown, rag chunks, llm ingestion, chunking, vector database.

### Features

- PDF and DOCX by URL or from an Apify key-value store record. The type is detected from the file content, not the extension.
- PDF: headings detected by font size (`#`, `##`, `###`), tables become GitHub Markdown tables, repeated headers/footers and page numbers are removed.
- DOCX: heading styles, bullet lists and tables kept in document order; headers and footers are ignored.
- Chunks follow the heading structure: each has `heading_path` (e.g. `["Report", "Costs"]`), `page`, `token_count` and a stable `id`. Tables are never cut mid-row (large tables split by rows, header row repeated). Consecutive chunks of a section overlap by the number of tokens you choose.
- One dataset item per input entry. A bad file gives an item with `error` set; the run continues and exits 0.

### Input

| Field | Type | Default | Description |
|---|---|---|---|
| `urls` | array, required | - | http(s) URLs, or `kvs:<key>` / `kvs:<storeIdOrName>/<key>` for key-value store records |
| `chunkSize` | integer | 500 | Max tokens per chunk (min 50). Counts are approximate |
| `overlap` | integer | 50 | Tokens repeated from the previous chunk of the same section. Must be below `chunkSize`, otherwise clamped with a warning |
| `outputFormat` | `markdown` | `chunks` | `both` | `both` | What each item contains |

```json
{
  "urls": ["https://example.com/brief.docx", "kvs:my-store/report.pdf"],
  "chunkSize": 500,
  "overlap": 50,
  "outputFormat": "both"
}
```

### Output

One item per input entry: `url, fileName, type (pdf|docx|null), title, pages, markdown, chunks[{id, text, heading_path, page, token_count}], chunkCount, warnings, error`. Example (trimmed, from the test run on `tests/samples/brief.docx`):

```json
{
  "url": "https://example.com/brief.docx",
  "fileName": "brief.docx",
  "type": "docx",
  "title": "Project Brief",
  "pages": 1,
  "chunkCount": 4,
  "warnings": [],
  "error": null,
  "markdown": "# Project Brief\n\nThe pipeline reads every document once and keeps the structure intact. Headings stay headings, tables stay tables and the text keeps its order. Each section is cut into passages that fit an embedding model. The pi…",
  "chunks": [
    {
      "id": "e4a9aad6-0001",
      "text": "# Project Brief\n\nThe pipeline reads every document once and keeps the structure intact. Headings stay headings…",
      "heading_path": ["Project Brief"],
      "page": null,
      "token_count": 79
    },
    {
      "id": "e4a9aad6-0003",
      "text": "## Budget\n\n| Item | Cost |\n|---|---|\n| Servers | 100 |\n| Support | 50 |…",
      "heading_path": ["Project Brief", "Budget"],
      "page": null,
      "token_count": 27
    }
  ]
}
```

### Pricing

Pay per event: **$0.02 per page** (event `page`). Charged only after a document converts successfully. Failed documents and PDFs with no text layer are free. DOCX has no pages: pages = max(1, ceil(words / 500)), and the same number is billed. If your spending limit is reached, the run stops and adds a warning; remaining entries are reported as skipped.

### Limits

- No OCR: scanned PDF pages are skipped with the warning `page N: no text layer (scanned?), OCR not supported`.
- Token counts are approximate (words and punctuation marks), not those of a specific model tokenizer. Leave some headroom against your embedding model's limit.
- 100 MB per file, 60 s download timeout. Encrypted or corrupt files return an error item.
- DOCX chunks have `page: null`.

### Privacy

The actor only converts files you supply and only requests the URLs you give it. No crawling, no scraping, no collection of personal data.

### Push and publish

1. `npm i -g apify-cli`
2. `apify login`
3. `apify push` (from this folder)
4. Console -> the actor -> Publication -> Monetization: **Pay per event**, add event `page` at **$0.02**.
5. Set categories (AI, Developer tools).
6. Set the SEO title and description (use the title and intro above).
7. Publish.

### Local development

```
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt && .venv/bin/python tests/test_actor.py
```

Prints `OK` on success. `tests/make_samples.py` rebuilds the sample files (needs playwright with chromium and python-docx; the samples are committed).
Run the actor locally: put an `INPUT.json` in `storage/key_value_stores/default/` and run `.venv/bin/python -m src`.

# Actor input Schema

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

PDF/DOCX files: http(s) URLs (Apify key-value store record URLs work), or `kvs:<key>` / `kvs:<storeIdOrName>/<key>` for a key-value store record.

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

Maximum tokens per chunk (approximate count: words and punctuation).

## `overlap` (type: `integer`):

Tokens repeated from the end of the previous chunk inside the same section. Must be below chunk size, otherwise it is clamped.

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

What to put in each dataset item.

## Actor input object example

```json
{
  "urls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
  ],
  "chunkSize": 500,
  "overlap": 50,
  "outputFormat": "both"
}
```

# 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"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("badboxx_newlife/pdf-docx-to-markdown-chunks").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"] }

# Run the Actor and wait for it to finish
run = client.actor("badboxx_newlife/pdf-docx-to-markdown-chunks").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"
  ]
}' |
apify call badboxx_newlife/pdf-docx-to-markdown-chunks --silent --output-dataset

```

## MCP server setup

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

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/IjAj86JKhUBKcIe95/builds/31Plodt1q0OucYZDP/openapi.json
