# PDF & DOCX to Markdown for AI and RAG (`praised_tumbler/pdf-docx-to-markdown`) Actor

Document parser: convert PDF, DOCX, HTML and text files into clean Markdown with headings, tables and lists, plus optional RAG chunks. Scanned pages are read with built-in OCR. No external API, Cyrillic and legacy encodings supported.

- **URL**: https://apify.com/praised_tumbler/pdf-docx-to-markdown.md
- **Developed by:** [Maine Wayne](https://apify.com/praised_tumbler) (community)
- **Categories:** AI, Agents, 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 $3.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 & DOCX to Markdown for AI Agents and RAG

Turn **PDF, DOCX, HTML and text files** into clean **Markdown** with real structure: headings, paragraphs, bullet lists and tables. Optionally get **RAG-ready chunks** with heading and page references. No external API, no API keys, no OCR service: the conversion runs inside the Actor. Works with Cyrillic and other non-Latin text.

A document parser and PDF-to-text converter built for AI agents, LLM pipelines, knowledge bases, document search and anyone who needs readable text out of documents at scale.

### What it does

- **PDF**: reads the text layer with layout analysis. Headings are detected from font size, two-column pages are read column by column, wrapped lines are joined into paragraphs (hyphenated words are repaired), bullet lists and aligned tables become Markdown, repeated headers, footers and page numbers are removed.
- **DOCX**: headings, bold/italic, lists, tables, links. Images are skipped.
- **HTML**: the main content of a page as Markdown (navigation, banners and small forms dropped; relative links made absolute; older encodings such as **windows-1251** read correctly, also when the page does not declare its encoding). Pages built inside one big form or with layout tables, common on older government sites, are read too.
- **Plain text / Markdown**: passed through (UTF-8, UTF-16 and legacy 8-bit encodings).
- **Chunks (optional)**: pieces of about N tokens that follow document structure, with optional overlap, the nearest heading and the page range of each chunk.
- **Safety flags**: `hiddenTextChars` reports invisible text inside a PDF (useful to spot hidden prompt-injection text before feeding a document to an LLM).
- **Scanned PDFs (OCR)**: pages without a text layer are rendered and read with an OCR engine that runs inside the Actor (14 languages including Bulgarian, Russian, Greek). Text pages never use OCR, so mixed documents are handled page by page. A scanned page that carries only a stamp or a page number as real text is recognised as a scan and read with OCR too. Scanned pages are straightened and turned upright before reading.
- **Clear errors**: password-protected files, corrupt or oversized files, and documents that yield no text get a plain-language message and are **not billed**.

### Input

| Field | Description |
|---|---|
| `urls` | Public http(s) links to documents (up to 100 per run). robots.txt is respected, also for redirect targets. |
| `inlineDocuments` | Small files as base64: `[{"filename": "a.pdf", "contentBase64": "..."}]` (max 20 files, 8 MB total). A `data:...;base64,` prefix is accepted. |
| `includePages` | Add one Markdown string per PDF page. |
| `chunkSizeTokens` / `chunkOverlapTokens` | 0 = no chunks. Token counts are estimates. |
| `removeHeadersFooters` | Drop repeated headers, footers and page numbers (PDF, 3+ pages). |
| `maxPagesPerDocument` | Convert only the first N PDF pages (default 200, max 1000). |
| `maxFileSizeMb` | Skip larger files (default 25, max 50). |
| `ocr` | `auto` (default): scanned pages are read with OCR; `off`: scanned pages are skipped. |
| `ocrLanguages` | 1 to 3 languages of scanned text, e.g. `["bul", "eng"]` (default `eng`). |
| `maxOcrPagesPerDocument` | Cap on OCR'd pages per PDF (default 50, max 200). |

#### Example input

```json
{
    "urls": ["https://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf"],
    "chunkSizeTokens": 500,
    "chunkOverlapTokens": 50
}
```

### Output (one item per document)

```json
{
    "source": "https://.../report.pdf",
    "status": "ok",
    "format": "pdf",
    "title": "Quarterly Report 2026",
    "pageCount": 3,
    "pagesConverted": 3,
    "billedPages": 3,
    "ocrPages": 0,
    "ocrConfidence": null,
    "wordCount": 136,
    "hiddenTextChars": 0,
    "warnings": [],
    "markdown": "# Quarterly Report 2026\n\nThis report summarises...\n\n## Highlights\n\n- Revenue up 12 percent\n...",
    "chunks": [{ "index": 0, "text": "...", "tokens": 54, "heading": "Quarterly Report 2026", "pageStart": 1, "pageEnd": 1 }]
}
```

Failed documents are returned with `"status": "error"` and an `error` message.

### Ready-made examples

Saved examples you can open, run and copy:

- [Research paper PDF to Markdown with RAG chunks](https://apify.com/praised_tumbler/pdf-docx-to-markdown/examples/pdf-research-paper-to-markdown-rag-chunks)

### Pricing

Pay per event: a small fee per **document converted** (`document-processed`), a small fee per **text page** (`page-processed`: one PDF page with a text layer, or about 3,000 characters for DOCX, HTML and text) and a higher fee per **scanned page read with OCR** (`ocr-page-processed`). Failed documents are free; failed OCR pages are not billed. Set **Max cost per run** to cap spending: the Actor never converts or charges more than your limit allows and cuts a long PDF at the last affordable page (`truncated: true`). See the pricing panel on this page for current prices.

### Limits and honest notes

- OCR is statistical: always spot-check numbers and names in scanned pages. Use the right `ocrLanguages` and scans of 150 DPI or more. Tilted and sideways pages are corrected automatically; blurred or very small print still reduces accuracy. Standalone images: use the [Image OCR](https://apify.com/praised_tumbler/image-ocr-bulgarian-cyrillic) Actor.
- Layout analysis is heuristic. Simple documents, reports, papers and contracts work well; complex layouts (overlapping text boxes, text in vector drawings, rotated pages) can come out in a different reading order. Tables are detected when columns line up; merged cells are not supported.
- Bullet lists are detected from bullet characters or consistent indentation. Lists drawn as pictures cannot be detected.
- Legacy `.doc`/`.xls`/`.ppt`, encrypted files and images are not supported.
- Only the files you point it to are fetched (no crawling). Private network addresses are blocked.
- You are responsible for having the right to process the documents you submit.

### FAQ

**Does it send my documents to a third-party AI or API?** No. Files are processed inside the Actor run; nothing is sent to an outside conversion service.

**Does it work with Bulgarian, Russian, Greek and other scripts?** Yes. Text in a PDF's text layer is extracted as-is; scanned pages are read with OCR when you set the right `ocrLanguages` (for example `bul`, `rus`, `ell`).

**Can an AI agent call it?** Yes, through the Apify API or MCP server. Use `inlineDocuments` for small files or `urls` for public files.

**Why was my URL refused?** The site's robots.txt disallows automated access, the host is not public, or the file exceeds the size limit. The error message says which.

**What does a scanned page cost?** The OCR page fee shown in the pricing panel, instead of the text page fee. Set `ocr: off` to never use OCR.

**Why is a table not detected?** Tables are recognised from aligned columns in the text layer. Try `includePages` and check the page, or open an issue with an example.

### Related Actors

- [Excel, PowerPoint & CSV to Markdown / JSON](https://apify.com/praised_tumbler/excel-powerpoint-to-markdown-json): spreadsheets and slide decks for LLMs.
- [Image OCR](https://apify.com/praised_tumbler/image-ocr-bulgarian-cyrillic): text from images and photos.
- [PII Redactor](https://apify.com/praised_tumbler/pii-redactor-eu-gdpr): mask personal data and secrets before sharing a text or sending it to an LLM.
- [Invoice Data Extractor](https://apify.com/praised_tumbler/invoice-data-extractor-bulgaria-eu): invoices to structured JSON.

# Actor input Schema

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

Public http(s) links to PDF, DOCX, HTML or text files. Up to 100 per run. The site's robots.txt is respected.

## `inlineDocuments` (type: `array`):

Small files passed directly, e.g. \[{"filename": "a.pdf", "contentBase64": "JVBERi0..."}]. Maximum 20 files and 8 MB in total.

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

Adds a `pages` array with one Markdown string per PDF page.

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

0 = no chunks. Otherwise adds a `chunks` array with pieces of about this many tokens (estimated), split on headings/paragraphs/sentences, with heading and page references.

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

Trailing text repeated at the start of the next chunk. Must be smaller than the chunk size.

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

PDF only. Drops lines that repeat at the top or bottom of most pages (documents with 3+ pages).

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

Only the first N pages of longer PDFs are converted (and billed).

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

Larger files are skipped with an error (not billed).

## `ocr` (type: `string`):

auto = pages without a text layer (scans) are read with OCR and billed as OCR pages; off = scanned pages are skipped. Pages that have a text layer never use OCR.

## `ocrLanguages` (type: `array`):

Language(s) of scanned text, up to 3. Choose the real language: Bulgarian text needs 'bul'.

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

Caps how many scanned pages of one PDF are OCR'd (and billed as OCR pages).

## Actor input object example

```json
{
  "urls": [
    "https://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf"
  ],
  "inlineDocuments": [],
  "includePages": false,
  "chunkSizeTokens": 0,
  "chunkOverlapTokens": 0,
  "removeHeadersFooters": true,
  "maxPagesPerDocument": 200,
  "maxFileSizeMb": 25,
  "ocr": "auto",
  "ocrLanguages": [
    "eng"
  ],
  "maxOcrPagesPerDocument": 50
}
```

# Actor output Schema

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

All results of the run (JSON items of 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://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("praised_tumbler/pdf-docx-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://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf"] }

# Run the Actor and wait for it to finish
run = client.actor("praised_tumbler/pdf-docx-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://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf"
  ]
}' |
apify call praised_tumbler/pdf-docx-to-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,praised_tumbler/pdf-docx-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/Afh6yzJ4xTOupScPZ/builds/PXGH4cbFoa8wqMBQs/openapi.json
