# Document to Markdown for LLMs: PDF, Scan OCR, DOCX, PPTX, XLSX (`lupenfrei/doc-to-markdown`) Actor

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

## Pricing

from $0.20 / 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

## Document to Markdown for LLMs: PDF, Scan OCR, Word, PowerPoint, Excel

Turn **PDFs, scanned PDFs, Word, PowerPoint, Excel, EPUB, HTML and images** into clean **Markdown** that LLMs and RAG pipelines can use directly. One Actor, one output format, for all your files.

- **Text PDFs**: headings (from font sizes), paragraphs, lists and **tables as Markdown**. Running headers, footers and page numbers are removed, hyphenated line breaks are joined.
- **Scanned PDFs and images**: OCR with Tesseract 5 in **15 European languages**, chosen automatically. Only pages without a text layer are OCRed, so you only pay OCR where it is needed.
- **German umlauts done right**: on a real 1949 scan (Bundesgesetzblatt) our OCR reads **98 % of all words with ä/ö/ü/ß correctly** (character error rate 1.6 %). Many OCR models trained mostly on Chinese/English turn *Maßnahmen* into *MaBnahmen* and *für* into *fur*. See [OCR quality](#ocr-quality).
- **Tables** also as **JSON rows and CSV**.
- **RAG chunks** (optional): every chunk has its **heading path, page range and token count** (OpenAI `o200k_base` tokenizer), with overlap inside a section.
- **Metadata**: title, author, dates, detected language, page count, OCR confidence, token count.
- **E-invoices**: ZUGFeRD / Factur-X XML embedded in a PDF, and XRechnung XML (CII or UBL), returned as **structured JSON** (number, dates, seller, buyer, VAT ID, IBAN, totals, line items).
- **Batch input**: many URLs, files from an Apify key-value store, an uploaded file, or a **ZIP** with documents.
- **Private by design**: files are downloaded into the run, converted and deleted. Nothing is stored except your own output dataset. No third-party AI APIs.

### What does it cost?

Pay per event, no subscription:

| Event | Price | When |
|---|---|---|
| Document | **$0.002** | per converted file (failed files are free) |
| Page | **$0.0002** | per PDF page with a text layer, per slide/sheet, or per 3,000 characters for formats without pages |
| OCR page | **$0.0025** | per scanned page or image page read with OCR (instead of the page price) |

Plus a small start fee per run ($0.0002 per GB of memory, $0.0004 at the default 2 GB). Platform usage is included in these prices.

Examples: a 10-page text PDF costs **$0.004**. A 10-page scanned PDF costs **$0.027**. 1,000 text pages cost **$0.20**, 1,000 OCR pages **$2.50**.

Set **"Maximum cost per run"** in the run options: the Actor stops cleanly before it would exceed it and tells you which document was cut.

### Input

| Field | Default | Description |
|---|---|---|
| `startUrls` | sample PDF | URLs of documents (PDF, DOCX, PPTX, XLSX, EPUB, HTML, TXT, MD, CSV, XML, PNG, JPG, TIFF, WEBP, ZIP). Key-value store record URLs work too. |
| `uploadedFile` | – | Upload one file instead of a URL. |
| `ocrMode` | `auto` | `auto` (OCR scanned pages only), `always`, `never` |
| `ocrLanguage` | `auto` | `auto` or Tesseract codes: `deu`, `eng`, `fra`, `spa`, `ita`, `nld`, `por`, `pol`, `ces`, `swe`, `dan`, `fin`, `hun`, `ron`, `frk` (German Fraktur), combined with `+` |
| `chunking` | `false` | Return RAG chunks |
| `chunkSizeTokens` / `chunkOverlapTokens` | 512 / 50 | Chunk size and overlap |
| `includeTables` | `true` | Tables as JSON rows + CSV |
| `includePages` | `false` | Markdown per page with method (text/OCR) and OCR confidence |
| `includePlainText` | `false` | Plain text without Markdown |
| `pageMarkers` | `false` | `<!-- page N -->` markers in the Markdown |
| `removeHeadersFooters` | `true` | Drop repeating header/footer lines |
| `extractEInvoice` | `true` | ZUGFeRD / Factur-X / XRechnung to JSON |
| `maxPagesPerDocument` | 300 | Page limit per file |
| `maxOcrPagesPerDocument` | 100 | OCR page limit per file |
| `maxFileSizeMb` | 50 | Download size limit |
| `pdfPassword` | – | For password-protected PDFs |

Example: a scanned 1949 law gazette whose old text layer is poor, so OCR is forced, plus a Word file, with RAG chunks:

```json
{
  "startUrls": [
    { "url": "https://upload.wikimedia.org/wikipedia/commons/e/e6/Bundesgesetzblatt_Nr._1%2C_1949.pdf" },
    { "url": "https://example.com/report.docx" }
  ],
  "ocrMode": "always",
  "maxPagesPerDocument": 5,
  "chunking": true,
  "chunkSizeTokens": 800
}
```

### Output

One dataset item per document (shortened):

```json
{
  "url": "https://upload.wikimedia.org/wikipedia/commons/e/e6/Bundesgesetzblatt_Nr._1%2C_1949.pdf",
  "fileName": "Bundesgesetzblatt_Nr._1,_1949.pdf",
  "fileType": "pdf",
  "status": "ok",
  "title": "BGBl Teil I Nr. 1 Jahr 1949",
  "language": "de",
  "pageCount": 20,
  "textPages": 0,
  "ocrPages": 5,
  "ocrLanguage": "deu",
  "ocrConfidence": 94.3,
  "tokenCount": 5099,
  "markdown": "Bundesgesetzblatt\n\nAusgegeben in Bonn am 23. Mai 1949 ...\n\nDer Parlamentarische Rat hat am 23. Mai 1949 in Bonn am Rhein in öffentlicher Sitzung festgestellt, daß ...",
  "tables": [],
  "chunks": [{ "index": 0, "text": "...", "headingPath": [], "pageStart": 1, "pageEnd": 2, "tokenCount": 783 }],
  "eInvoice": null,
  "truncated": true,
  "warnings": ["Only the first 5 of 20 pages were processed (maxPagesPerDocument)."]
}
```

Other fields: `author`, `subject`, `creationDate`, `modificationDate`, `producer`, `charCount`, `wordCount`, `pages` (per-page Markdown), `processingSeconds`, `errorMessage` (for failed files, which are never charged). The dataset has the views **Overview**, **RAG chunks** and **Tables**.

Very large documents (> 8 MB of output) keep a preview in the dataset and the full result in the run's key-value store (`fullResultUrl`).

### OCR quality

Measured on the Apify platform with **1 CPU core**, same pages for every engine:

- **Real scan**: 5 pages of the 1949 *Bundesgesetzblatt* (two columns, yellowed paper, 190 dpi), ground truth from the proofread Wikisource transcription.
- **Office scans**: 4 German letters, reports, invoices and legal texts with scan noise, blur and 1–2° skew, at 300 and 150 dpi.

| Engine | Character errors, real scan | Words with ä/ö/ü/ß correct (real) | Words correct, 150 dpi scans | Seconds per page (real) | Memory |
|---|---|---|---|---|---|
| **This Actor (Tesseract 5 `deu`)** | **1.6 %** | **98 %** | **98 %** | **~6** | **~100 MB** |
| PaddleOCR PP-OCRv6 (RapidOCR 3.10 default) | 2.0 % | 98 % | 87 % | ~17 | ~700 MB |
| PaddleOCR PP-OCRv5 Latin model | 2.2 % | 98 % | 87 % | ~21 | ~690 MB |
| PaddleOCR PP-OCRv4 (older default) | 6.1 % | **0 %** ("fur", "MaBnahmen") | – | ~19 | ~700 MB |
| Tesseract with English model only | 4.0 % | 0 % | 72 % | ~5 | ~100 MB |

Full pipeline on the real scan (render, OCR, clean-up): 1.2–2.0 % character errors, 98–100 % of umlaut words correct, OCR confidence 94–95. Noisy low-resolution pages are retried automatically with denoising.

German, Austrian and Swiss documents are where this Actor is strongest. Handwriting is not supported. Heavily speckled scans below 150 dpi give weak results.

### Use with AI agents (MCP)

The Actor works as a tool in Apify's MCP server (`apify/actors-mcp-server`) and with the Apify API: give it a URL, get Markdown back. A typical call for one small PDF finishes in a few seconds. The input has sensible defaults, so `{"startUrls": [{"url": "..."}]}` is enough.

### Limits and good to know

- Legacy formats `.doc`, `.xls`, `.ppt` and HEIC images are not supported (save as `.docx`, `.xlsx`, `.pptx`, `.jpg`).
- Tables inside scanned pages are returned as text, not as table structure.
- URLs must be public. Private network addresses (localhost, 10.x, 192.168.x, cloud metadata) are blocked.
- ZIP files: max. 200 files, zip bombs are refused.

### Privacy and rights

You are responsible for having the right to process the documents you submit. The Actor processes files only inside your run and deletes them afterwards. It does not log document content. Results go only to your own dataset (and key-value store for very large results).

### Open-source components

Tesseract OCR and tessdata models (Apache-2.0), pypdfium2/PDFium (Apache-2.0/BSD-3), pdfplumber and pdfminer.six (MIT), markitdown (MIT), mammoth (BSD-2), python-pptx and openpyxl (MIT), pandas (BSD-3), Beautiful Soup (MIT), markdownify (MIT), tiktoken (MIT), defusedxml (PSF), Pillow (MIT-CMU), httpx (BSD-3).

# Actor input Schema

## `startUrls` (type: `array`):

Public URLs of the documents to convert: PDF (text or scanned), DOCX, PPTX, XLSX, EPUB, HTML, TXT/MD/CSV, XML e-invoices, images (PNG, JPG, TIFF, WEBP) or a ZIP with such files. Files uploaded to an Apify key-value store work too (use the record URL).

## `uploadedFile` (type: `string`):

Upload one document from your computer instead of giving a URL.

## `ocrMode` (type: `string`):

auto = OCR only pages without a usable text layer (scans). always = OCR every page (e.g. broken text layers). never = text layer only, no OCR charges.

## `ocrLanguage` (type: `string`):

auto = detect the language from the text layer or a first OCR pass. Or Tesseract codes joined with +, e.g. deu, deu+eng, fra, spa, ita, nld, por, pol, ces, swe, dan, fin, hun, ron, frk (German Fraktur).

## `chunking` (type: `boolean`):

Also return chunks for vector databases: each chunk has its heading path, page range and token count (OpenAI o200k tokenizer).

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

Maximum tokens per chunk.

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

Tokens of the previous chunk repeated at the start of the next one (within the same section).

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

Return every detected table additionally as rows (JSON) and CSV. Tables are always included in the Markdown.

## `includePages` (type: `boolean`):

Return the Markdown of every page separately, with the method used (text layer or OCR) and the OCR confidence.

## `includePlainText` (type: `boolean`):

Also return the content as plain text without Markdown syntax.

## `pageMarkers` (type: `boolean`):

Insert  comments into the Markdown so citations can point to pages.

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

Drop lines that repeat at the top or bottom of most PDF pages (page numbers, document titles).

## `extractEInvoice` (type: `boolean`):

If a PDF carries an embedded invoice XML (ZUGFeRD / Factur-X) or the file is an XRechnung XML, return the invoice data as JSON (number, dates, seller, buyer, totals, line items).

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

Pages beyond this limit are skipped (and not charged). For formats without pages, 3,000 characters count as one page.

## `maxOcrPagesPerDocument` (type: `integer`):

Upper limit for OCR pages per document, to keep costs predictable.

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

Larger downloads are refused.

## `pdfPassword` (type: `string`):

Password for protected PDFs (used for all PDFs in this run).

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://upload.wikimedia.org/wikipedia/commons/5/5e/%C3%9Cbersicht_Verwaltungskompetenzen.pdf"
    }
  ],
  "ocrMode": "auto",
  "ocrLanguage": "auto",
  "chunking": false,
  "chunkSizeTokens": 512,
  "chunkOverlapTokens": 50,
  "includeTables": true,
  "includePages": false,
  "includePlainText": false,
  "pageMarkers": false,
  "removeHeadersFooters": true,
  "extractEInvoice": true,
  "maxPagesPerDocument": 300,
  "maxOcrPagesPerDocument": 100,
  "maxFileSizeMb": 50
}
```

# Actor output Schema

## `documents` (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 = {
    "startUrls": [
        {
            "url": "https://upload.wikimedia.org/wikipedia/commons/5/5e/%C3%9Cbersicht_Verwaltungskompetenzen.pdf"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("lupenfrei/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 = { "startUrls": [{ "url": "https://upload.wikimedia.org/wikipedia/commons/5/5e/%C3%9Cbersicht_Verwaltungskompetenzen.pdf" }] }

# Run the Actor and wait for it to finish
run = client.actor("lupenfrei/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 '{
  "startUrls": [
    {
      "url": "https://upload.wikimedia.org/wikipedia/commons/5/5e/%C3%9Cbersicht_Verwaltungskompetenzen.pdf"
    }
  ]
}' |
apify call lupenfrei/doc-to-markdown --silent --output-dataset

```

## MCP server setup

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