# Document to Markdown & RAG Chunks (PDF, Word, Excel, CJK) (`fontom.ai.plus/document-to-markdown`) Actor

PDF, DOCX, XLSX, PPTX, HTML and CSV to clean Markdown, text and RAG chunks. Two-column PDFs and Japanese/Chinese/Korean text handled. No OCR, no AI guessing, no third-party API.

- **URL**: https://apify.com/fontom.ai.plus/document-to-markdown.md
- **Developed by:** [FONTOM AI](https://apify.com/fontom.ai.plus) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $10.00 / 1,000 results

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 & RAG Chunks — PDF, Word, Excel, PowerPoint, HTML (CJK-ready)

**Run it on Apify Store:** https://apify.com/fontom.ai.plus/document-to-markdown

Turn documents into **clean Markdown, plain text and RAG-ready chunks** for LLM agents, search indexes and data pipelines. Pure code running inside the Actor: **no OCR service, no AI guessing, no third-party API, no API keys.**

### What makes the output good

- **Two-column PDFs are read in the right order** (left column, then right; full-width titles first). Most simple extractors interleave the columns line by line.
- **PDF tables come out as real Markdown tables** (header row, right-aligned numbers, wrapped cell text, Japanese tables), found from the alignment of the text itself. Turn it off with `detectTables: false`.
- **Headings, bullet lists and wrapped paragraphs** in PDFs are rebuilt from font sizes and positions; page-by-page text is included.
- **Japanese / Chinese / Korean text works**: no stray spaces inside words, and PDFs that encode characters as Kangxi radicals (⽇ ⺠ ⽂ instead of 日 民 文, common in Wikipedia and government PDFs) are folded back to normal ideographs so search and embeddings match. Optional NFKC normalisation for full-width letters and digits.
- **Word** (headings, lists, tables), **Excel** (every sheet as a Markdown table), **PowerPoint** (slide by slide, titles, bullets, speaker notes), **HTML** (main content only: navigation, headers, footers, forms, scripts and images dropped), **CSV / TXT / MD**.
- **Shift_JIS, EUC-JP and UTF-16 files are decoded correctly** (Japanese government CSVs and older sites are often not UTF-8). The detected encoding is reported when it is not UTF-8.
- **Scanned PDFs are flagged clearly**: `scanned: true`, the page numbers without a text layer, and a warning, so a pipeline can route them to OCR.
- **RAG chunks** (optional): paragraph- and sentence-aware, with overlap and the page range of every chunk.
- **Safe by design**: only public http(s) URLs (private, local and cloud-metadata addresses are blocked, also after redirects), file size and page limits.

### Input

| Field | Meaning |
|---|---|
| `urls` | Public document URLs (up to 5,000 per run). |
| `documents` | Optional inline files: `[{"name": "a.pdf", "base64": "..."}]`. |
| `chunkSize` | Characters per chunk (0 = off; 1000–2000 typical). `chunkOverlap` (default 150). |
| `maxPages`, `maxFileMb`, `maxChars` | Limits (defaults 500 pages, 50 MB, 2,000,000 characters). |
| `includePageTexts` | Page-by-page text for PDFs (default on). |
| `detectTables` | Turn aligned PDF text into Markdown tables (default on). Switch off to get plain lines. |
| `fixCjkVariants` | Fold Kangxi-radical/compatibility glyphs (default on). `normalize` = NFKC (default off). |

### Output (one row per document)

```json
{ "ok": true, "source": "https://example.com/report.pdf", "type": "pdf", "title": "…", "pages": 12, "script": "ja",
  "chars": 18234, "markdown": "# …", "text": "…", "pageTexts": ["…"], "chunks": [{ "index": 0, "text": "…", "chars": 1432, "pages": [1, 2] }],
  "warnings": [] }
```

`script` is `ja`, `zh`, `ko`, `latin`, `other` or `unknown`, detected from the characters present. `tables` counts the Markdown tables found in a PDF. `scanned` / `emptyPages` appear for PDFs without a text layer, `encoding` for files that were not UTF-8. `warnings` tells you when something was skipped.

### Pricing

Pay per event, as shown on the Actor page: a tiny **start fee per run** ($0.00005) plus **one charge per result row** ($0.01) (Apify's dataset-item event). **Every row is charged, including rows for documents that failed to convert** (404, blocked address, unsupported type, too large), so check URLs before big batches. One run can hold up to 5,000 documents.

### Limits, stated plainly

- **No OCR.** Scanned or image-only PDFs return a warning ("no text layer"), not text.
- **Vertical (tategaki) Japanese** reading order is not reconstructed (a warning is raised when it is detected).
- **PDF tables are inferred from text alignment**, so they are only as good as the layout: borderless tables, merged header cells and tables that continue across pages can be split or mis-aligned, and infographics or figure labels are occasionally turned into a small table. Tables that sit beside body text in a two-column page are read as text. Use `detectTables: false` if you prefer plain lines.
- Legacy `.doc`, `.xls`, `.ppt` are not supported (save as `.docx`, `.xlsx`, `.pptx`). Password-protected files fail with an error row.
- Layout-heavy PDFs (magazines, posters, forms) can come out in an imperfect reading order. Multi-column detection handles the common two-column paper/report layout only.
- Only documents you are allowed to process: you are responsible for the rights to the files you convert.

Tested on real, public documents (conversion time on a laptop, tables found in the PDF): *Attention Is All You Need* (15 pages), *BERT* (16), *LLaMA* (27), *GPT-3* (75, 244k characters), the Japanese National Tax Agency invoice-system leaflets (27 and 4 pages), the Ministry of Internal Affairs and Communications white-paper index tables (8 pages, long Japanese tables spanning pages), a Wikipedia Japanese PDF, the e-Gov law Word files and a Japanese HTML page, plus unit tests for every file type and for tables, text columns, wrapped cells, Japanese tables, Shift_JIS/EUC-JP files and scanned pages. The check script is `scripts/benchmark.mjs`.

# Actor input Schema

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

Public http(s) URLs. Private/internal addresses are blocked. Up to 5,000 per run.

## `documents` (type: `array`):

Files you already have, as \[{"name": "report.pdf", "base64": "..."}].

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

0 = no chunks. 1000–2000 is typical for embeddings. Chunks follow paragraph and sentence boundaries and keep page numbers.

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

Characters repeated at the start of the next chunk so context is not lost at boundaries (default 150).

## `maxPages` (type: `integer`):

PDFs with more pages are converted up to this page and a warning is added.

## `includePageTexts` (type: `boolean`):

Adds pageTexts (one plain-text string per page) to PDF results. Turn off to make rows smaller.

## `detectTables` (type: `boolean`):

Turn aligned text in PDFs into Markdown tables. Switch off to get plain text lines instead (useful if a layout is mistaken for a table).

## `fixCjkVariants` (type: `boolean`):

Many PDFs encode characters as Kangxi radicals (⽇ instead of 日). This folds exactly those code points back to normal ideographs.

## `normalize` (type: `boolean`):

Also turns full-width letters/digits into ASCII, half-width kana into full-width, ㈱ into (株). Useful for search; changes the text.

## `maxFileMb` (type: `integer`):

Larger files fail with an error row (free). Maximum 100.

## `maxChars` (type: `integer`):

Output is cut at this length and a warning is added.

## Actor input object example

```json
{
  "urls": [
    "https://arxiv.org/pdf/1706.03762"
  ],
  "chunkSize": 0,
  "chunkOverlap": 150,
  "maxPages": 500,
  "includePageTexts": true,
  "detectTables": true,
  "fixCjkVariants": true,
  "normalize": false,
  "maxFileMb": 50,
  "maxChars": 2000000
}
```

# Actor output Schema

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

Converted documents in the default dataset.

# 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://arxiv.org/pdf/1706.03762"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("fontom.ai.plus/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://arxiv.org/pdf/1706.03762"] }

# Run the Actor and wait for it to finish
run = client.actor("fontom.ai.plus/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://arxiv.org/pdf/1706.03762"
  ]
}' |
apify call fontom.ai.plus/document-to-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,fontom.ai.plus/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/u5U17nC8qBgqHqpzL/builds/J9XT3Gxeb0sByK9mK/openapi.json
