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

Convert PDF, DOCX, PPTX, XLSX, CSV, HTML and Korean HWP/HWPX (beta) files you supply into Markdown, tables and RAG chunks with heading paths and PDF page numbers. Text-layer files only: no OCR, no web scraping. $0.004 per document + $0.0003 per page. Failed files are free.

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

## Pricing

from $4.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

**Document to Markdown for RAG** converts PDF, DOCX, PPTX, XLSX, CSV, HTML, TXT/MD and Korean HWP/HWPX (beta) files into Markdown, tables and RAG chunks with heading paths and, for PDF, PPTX and XLSX, page numbers.
It is for developers who feed documents to LLMs, vector databases and search indexes, and for teams that need Korean HWP files as text.
Pricing: **$0.004 per document + $0.0003 per page** (a 20-page PDF is $0.010). Failed files and files with no extractable text are not charged.

#### What you get

- One dataset item per document: `markdown`, `tables` (rows of cells), `chunks` (with metadata), `warnings`, and an `error` object when a file fails.
- Chunks follow the document structure: a new heading starts a new chunk, chunks stay under your token budget, and they overlap inside a section. Each chunk has `index`, `page` (PDF page, PPTX slide or XLSX sheet number; `null` for other formats), `headingPath`, `tokenCount`, `charStart` and `charEnd`. `chunks[].text` is exactly `markdown[charStart:charEnd]`, so you can cite a source position.
- Headings, numbered and bulleted lists (with nesting) and tables are kept as Markdown. Merged table cells become a rectangular grid.
- Deterministic in our tests: the same file and settings gave byte-identical output on repeat runs, so re-indexing stays stable.
- It reads only the files you give it (HTTP(S) links, files in your key-value store, or inline text). It does not crawl or scrape websites and does not run OCR.

#### Supported formats

| Format | Extensions | Notes |
|---|---|---|
| PDF (with a text layer) | `.pdf` | Headings guessed from font size, ruled tables, page numbers |
| Word | `.docx`, `.docm` (macros not run) | Headings, nested lists, tables |
| PowerPoint | `.pptx` | Slide titles, text, speaker notes, tables; slide number as page |
| Excel | `.xlsx`, `.xlsm` | One section and table per sheet (cached values) |
| CSV / TSV | `.csv`, `.tsv` | UTF-8, UTF-16 (with BOM), CP949 or Latin-1 |
| HTML, text | `.html`, `.htm`, `.txt`, `.md` | |
| Hangul (beta) | `.hwpx`, `.hwp` (5.x) | Text, headings, lists, tables |

#### Input example

```json
{
  "files": [
    "https://example.com/reports/annual-report.pdf",
    {"key": "contract.hwp"},
    {"fileName": "notes.md", "text": "# Notes\n\n- first\n- second"}
  ],
  "outputMode": "both",
  "chunkSize": 800,
  "chunkOverlap": 100,
  "includeTables": true
}
```

The pre-filled input is a small inline HTML document, so the first run works without any external file. `{"key": ...}` items need a key-value store selected in "Key-value store with your files". Google Drive, Dropbox and OneDrive share-page links return a web page, not the file, and fail with `SHARE_PAGE_NOT_FILE`; use a direct download link.

#### Output example (real run)

Run on the public NIST Cybersecurity Framework 2.0 PDF (32 pages), first 3 pages only (`maxPagesPerFile: 3`). Long text is shortened with "...". Every real item also has `inputIndex`, a `tables` list and `fullOutput`, left out here.

```json
{
  "fileName": "en03_spec.pdf",
  "format": "pdf",
  "pageCount": 32,
  "charCount": 2818,
  "markdown": "# The NIST Cybersecurity Framework (CSF) 2.0\n\n## National Institute of Standards and Technology\n\nThis publication is available free of charge from: https://doi.org/10.6028/NIST.CSWP.29 February 26, 2024 Abstract\n\nThe NIST Cybersecurity Framework (CSF) 2.0 provides guidance to industry, government agencies, and other organizations to manage cybersecurity risks. ...",
  "chunks": [
    {"index": 1,
     "text": "not used for CSF 2.0.\n\ni Acknowledgments\n\nThe CSF is the result of a multi-year collaborative effort ...",
     "tokenCount": 130, "page": 2,
     "headingPath": ["The NIST Cybersecurity Framework (CSF) 2.0", "National Institute of Standards and Technology"],
     "charStart": 2363, "charEnd": 2817}
  ],
  "warnings": ["Only the first 3 of 32 pages were processed (maxPagesPerFile)."],
  "error": null
}
```

This sample also shows two imperfections. The title-page text and the word "Abstract" ended up in one paragraph, and the chunk starts mid-sentence because chunks are cut by token budget inside a section. On a 48-page NIST AI RMF PDF the title block came out twice at the top. Check the output on your own documents.

#### Use cases

1. **RAG indexing with citations.** Convert a folder of PDFs and Word files, embed `chunks[].text`, and store `page`, `headingPath` and `charStart`/`charEnd` as metadata so an answer can point to a page and a heading.
2. **Feeding long documents to an LLM.** Turn reports, slide decks and spreadsheets into Markdown that keeps headings, lists and tables, before summarising or extracting fields.
3. **Korean government and enterprise documents.** HWP and HWPX files, common in Korean public-sector work, come out as text, headings and tables (beta). In our check, 2 HWPX files and 1 HWP file from public Korean sources converted without errors.

#### Pricing

Pay per event:

| Event | When | Price |
|---|---|---|
| `document-processed` | Each document converted successfully | $0.004 |
| `page-processed` | Each PDF page or PPTX slide processed. Other formats: each started block of 3,000 Markdown characters | $0.0003 |

Examples: a 20-page text PDF = $0.004 + 20 x $0.0003 = **$0.010**. A 48-page PDF = $0.0184. A DOCX under 3,000 characters = $0.0043.
Apify's standard run-start event is charged by the platform separately. Failed files, timeouts and files with no extractable text are not charged. A PDF that is only partly image-based is charged for every page processed, including image-only pages. The run stops cleanly when your maximum charge limit is reached.

#### Limits (please read)

We checked this Actor by reading its output for 28 real public documents (Korean and English PDFs, DOCX, XLSX, PPTX, HWPX, HWP). Coverage outside PDF is thin: 2 DOCX (both Korean), 2 XLSX, 1 PPTX, 2 HWPX and 1 HWP. We do not claim an accuracy percentage. Our own rough grading: about 12 were usable as they came out, 15 needed cleanup, and 1 (a 359-page NASA scan with a broken text layer) was not usable. Known problems:

- **No OCR.** Image-only pages return no text and a warning. A scanned PDF that already has an OCR text layer is read as-is, and that layer's mistakes (for example stuck-together words) come through unchanged.
- **Statistics tables without ruling lines can come out misaligned.** Rows and columns may not line up, row labels in an unruled label column may be lost, and some numbers end up as lines of text. LaTeX "booktabs" tables are usually flattened to text lines instead of being recovered as tables. Only ruled tables are detected reliably. Check statistics-heavy documents by eye.
- **Footnote numbers can end up in the body text**, for example a footnote marker glued to the next word.
- **Layout:** two-column pages are read column by column, but three or more columns, magazine layouts and slide-style PDFs can still come out in a mixed order. Text inside figures (axis labels, chart numbers) can appear as stray words, table-of-contents dot leaders come through as text, and a title block can be repeated at the top.
- **Hyphenation:** a line-end hyphen is removed only when the joined word occurs elsewhere in the same document, so some `representa- tion` style breaks remain.
- **PDFs with a broken text layer:** a page where more than 30% of the glyphs have no Unicode mapping is dropped with a warning and is not billed.
- **Korean public documents:** some bullets are not turned into lists, letter-spaced titles stay spaced out, and text that has no spaces in the PDF itself stays without spaces.
- **DOCX:** text boxes, headers/footers, footnotes, comments and tracked changes are not extracted. **XLSX:** formulas are not recalculated; a formula without a saved value comes out empty.
- **HWP/HWPX are beta.** Footnotes, headers/footers, text boxes, equations and images are not extracted. HWP 5.x numbering styles are written as `1.` `2.`. Encrypted and DRM HWP files are rejected.
- Not supported: password-protected files, legacy `.doc`/`.xls`/`.ppt`, HWP 3.x. A per-file size limit (default 50 MB, max 200 MB) and a time limit apply.

#### FAQ

**Does it crawl websites?** No. It fetches only the exact file URLs you list, or records in your key-value store.

**Can it read scanned PDFs?** Only if the PDF already has a text layer. There is no OCR. Image-only pages give a warning and no text.

**How are tables handled?** Each table becomes a Markdown table and a rectangular `rows` grid. Merged cells keep the value at the top-left position and the covered cells are empty strings. PDF tables are reliable only when they have ruling lines.

**How does chunking work?** A heading starts a new chunk. Inside a section, chunks fill up to `chunkSize` tokens (default 800), preferring sentence and line ends, and overlap by `chunkOverlap` tokens (default 100). Token counts are an approximation, not a model tokenizer; leave 10-15% headroom if your embedding model has a hard limit.

**What happens to a broken file?** You get an item with `markdown: null` and an `error` such as `INVALID_FILE`, and the other files still run. Set `failOnError` to stop at the first error.

**Are password-protected files supported?** No. They are rejected and not charged.

**What if a document is huge?** If an item would exceed 8 MB, the dataset item holds a preview and `fullOutput` points to the complete Markdown, chunks and tables in the run's key-value store.

**What happens to my files?** They are converted in memory during the run and discarded. Results stay in your run's dataset and key-value store in your Apify account. Nothing is sent to a third party.

**What is it built with?** Permissive-license libraries (pdfplumber, python-docx, python-pptx, openpyxl, BeautifulSoup and others). The Actor was developed with AI assistance (Claude by Anthropic).

HWP format attribution: 본 제품은 한글과컴퓨터의 한/글 문서 파일(.hwp) 공개 문서를 참고하여 개발하였습니다. Microsoft Word, PowerPoint and Excel are trademarks of Microsoft; Hancom and Hangul are trademarks of Hancom Inc. This Actor is not affiliated with or endorsed by them.

# Changelog

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

# Actor input Schema

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

Documents to convert. Each item is one of: a direct HTTP(S) URL to a file you own (string or {"url": "..."}); inline content {"fileName": "notes.md", "text": "..."} (up to 1 MB of text; the file extension picks the format, e.g. .html, .md, .csv, .txt); a record in the key-value store selected below {"key": "KEY"}; or a public Apify key-value store record URL (https://api.apify.com/v2/key-value-stores/STORE_ID/records/KEY). Supported: PDF (text-based), DOCX, PPTX, XLSX, CSV/TSV, HTML, TXT, MD, HWPX (beta), HWP 5.x (beta). The Actor never crawls websites: only the listed files are downloaded. The prefilled example is a small inline HTML document so the first run works without any external URL.

## `keyValueStore` (type: `string`):

Optional. Select a key-value store that holds your documents. If "Files" is empty, every record in this store (except INPUT, max 1,000) is converted; otherwise {"key": "..."} items in "Files" are read from it. Selecting the store here grants this Actor read access to it, which works with Apify's default limited permissions.

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

What to return per document: the full Markdown, only the RAG chunks, or both.

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

Maximum tokens per chunk (approximate token count, see README).

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

Tokens repeated between consecutive chunks inside the same section. Must be smaller than the chunk size.

## `includeTables` (type: `boolean`):

Detect tables, render them as Markdown tables and return their cells in the 'tables' field. When off, table text is kept as plain lines.

## `maxPagesPerFile` (type: `integer`):

Optional cap on pages (PDF), slides (PPTX) or sheets (XLSX) processed per file. Leave empty for no cap.

## `failOnError` (type: `boolean`):

Off (default): a broken file produces a dataset item with an 'error' object and the run continues. On: the run fails at the first file error.

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

Files larger than this are rejected with a FILE_TOO_LARGE error (hard limit 200 MB).

## `perFileTimeoutSecs` (type: `integer`):

Download and conversion of a single file are each stopped after this many seconds (max 300). The download limit is a hard wall-clock deadline.

## Actor input object example

```json
{
  "files": [
    {
      "fileName": "example.html",
      "text": "<h1>Quarterly Report</h1><p>Revenue grew in every region. 모든 지역에서 매출이 증가했습니다.</p><h2>Next steps</h2><ol><li>Expand to two new markets</li><li>Launch the mobile app<ol><li>Beta in Q1</li><li>Release in Q2</li></ol></li></ol><h2>Regional results</h2><table><tr><th rowspan=\"2\">Region</th><th colspan=\"2\">2026 revenue</th></tr><tr><th>H1</th><th>H2</th></tr><tr><td>Seoul</td><td>100</td><td>120</td></tr><tr><td>Busan</td><td>80</td><td>95</td></tr></table>"
    }
  ],
  "outputMode": "both",
  "chunkSize": 800,
  "chunkOverlap": 100,
  "includeTables": true,
  "failOnError": false,
  "maxFileSizeMb": 50,
  "perFileTimeoutSecs": 120
}
```

# Actor output Schema

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

No description

## `fullOutputs` (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 = {
    "files": [
        {
            "fileName": "example.html",
            "text": "<h1>Quarterly Report</h1><p>Revenue grew in every region. 모든 지역에서 매출이 증가했습니다.</p><h2>Next steps</h2><ol><li>Expand to two new markets</li><li>Launch the mobile app<ol><li>Beta in Q1</li><li>Release in Q2</li></ol></li></ol><h2>Regional results</h2><table><tr><th rowspan=\"2\">Region</th><th colspan=\"2\">2026 revenue</th></tr><tr><th>H1</th><th>H2</th></tr><tr><td>Seoul</td><td>100</td><td>120</td></tr><tr><td>Busan</td><td>80</td><td>95</td></tr></table>"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("aaron_lee/document-to-markdown-rag-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 = { "files": [{
            "fileName": "example.html",
            "text": "<h1>Quarterly Report</h1><p>Revenue grew in every region. 모든 지역에서 매출이 증가했습니다.</p><h2>Next steps</h2><ol><li>Expand to two new markets</li><li>Launch the mobile app<ol><li>Beta in Q1</li><li>Release in Q2</li></ol></li></ol><h2>Regional results</h2><table><tr><th rowspan=\"2\">Region</th><th colspan=\"2\">2026 revenue</th></tr><tr><th>H1</th><th>H2</th></tr><tr><td>Seoul</td><td>100</td><td>120</td></tr><tr><td>Busan</td><td>80</td><td>95</td></tr></table>",
        }] }

# Run the Actor and wait for it to finish
run = client.actor("aaron_lee/document-to-markdown-rag-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 '{
  "files": [
    {
      "fileName": "example.html",
      "text": "<h1>Quarterly Report</h1><p>Revenue grew in every region. 모든 지역에서 매출이 증가했습니다.</p><h2>Next steps</h2><ol><li>Expand to two new markets</li><li>Launch the mobile app<ol><li>Beta in Q1</li><li>Release in Q2</li></ol></li></ol><h2>Regional results</h2><table><tr><th rowspan=\\"2\\">Region</th><th colspan=\\"2\\">2026 revenue</th></tr><tr><th>H1</th><th>H2</th></tr><tr><td>Seoul</td><td>100</td><td>120</td></tr><tr><td>Busan</td><td>80</td><td>95</td></tr></table>"
    }
  ]
}' |
apify call aaron_lee/document-to-markdown-rag-chunks --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,aaron_lee/document-to-markdown-rag-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/5PRsaRbJuUDwqBwdU/builds/Qr4ghBaXDx6TwIV7n/openapi.json
