# PDF, DOCX and HTML to Markdown Converter (RAG) (`clearcheck/document-to-markdown-converter`) Actor

Convert PDF, DOCX and HTML files to clean Markdown from URLs or uploaded files, with titles, lists, tables and optional RAG-ready chunks for LLM pipelines.

- **URL**: https://apify.com/clearcheck/document-to-markdown-converter.md
- **Developed by:** [ClearCheck Tools](https://apify.com/clearcheck) (community)
- **Categories:** AI, Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 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

## PDF, DOCX and HTML to Markdown Converter (RAG)

Turn PDF, Word (DOCX) and web page (HTML) files into **clean, structured Markdown** that LLMs and vector databases can use directly. Give it URLs or files you uploaded to Apify storage and get back, for each document: Markdown with headings, lists and tables, metadata (title, author, page count, detected language), and optional **RAG-ready chunks** with configurable size and overlap.

No external API, no AI service, no OCR bill: conversion runs inside the Actor, so it is fast and cheap.

### What you get

- **PDF**: headings detected from font sizes, bullet and numbered lists, tables with aligned columns turned into Markdown tables, repeated headers and footers removed, page count and PDF metadata (title, author, dates).
- **DOCX**: Word headings and title styles, lists, tables, bold/italic, links; document properties (title, author, dates).
- **HTML**: main article extraction (menus, ads, footers dropped), links made absolute, tables, lists, code blocks.
- **Language detection** for every document (ISO 639-1 code such as `en`, `fr`, `de`).
- **RAG chunking**: cuts along headings and paragraphs (tables and lists stay in one piece when they fit), overlap you control, and for every chunk: heading path, page range (PDF), exact character offsets, token estimate.
- **Two dataset layouts**: one item per document, or flat `{id, text, metadata}` rows per chunk, ready to upsert into a vector store.
- Failed documents never stop the run and are never charged.

### Quick start

1. Open the Actor, paste one or more URLs in **Document URLs**.
2. (Optional) turn on **Split into chunks for RAG**.
3. Click **Start**, then open the **Output** tab or download the dataset as JSON, CSV or Excel.

#### Using your own files

Create a key-value store in Console (Storage > Key-value stores), upload your files as records, then put their keys in **Uploaded files** and the store name or ID in **Key-value store ID or name**.

### Input

| Field | Description | Default |
|---|---|---|
| `urls` | Public URLs of PDF, DOCX or HTML documents. Format is detected from content. | - |
| `kvStoreKeys`, `kvStoreId` | Files stored in a key-value store. | - |
| `extractMainContent` | HTML: keep only the main article. | `true` |
| `maxPagesPerDocument` | Convert only the first N pages of each PDF (0 = all). | `0` |
| `maxFileSizeMb` | Skip larger files (not charged). | `50` |
| `pdfPassword` | Password for protected PDFs (secret). | - |
| `enableChunking` | Add chunks to each document. | `false` |
| `chunkSize`, `chunkOverlap` | In characters (about 4 characters per token). | `1500`, `200` |
| `outputMode` | `documents` or `chunks`. | `documents` |
| `saveMarkdownFiles` | Also store each result as a `.md` file in the run's key-value store. | `false` |

Example input:

```json
{
  "urls": ["https://example.com/annual-report.pdf", "https://example.com/blog/post.html"],
  "enableChunking": true,
  "chunkSize": 1200,
  "chunkOverlap": 150
}
```

### Output

Default layout (`outputMode: "documents"`), abridged (real output of the test PDF):

```json
{
  "id": "f26767130f",
  "source": { "type": "url", "url": "https://example.com/report.pdf" },
  "status": "ok",
  "format": "pdf",
  "metadata": {
    "title": "Annual Climate Report 2025",
    "author": "Jane Doe",
    "pages": 13,
    "pagesEstimated": false,
    "language": "en",
    "wordCount": 933,
    "characterCount": 6719,
    "tokensEstimate": 1680,
    "createdAt": "2026-11-19T12:59:37Z"
  },
  "markdown": "# Annual Climate Report 2025\n\n...\n\n| Region | Stations | Trend (C/decade) |\n| --- | --- | --- |\n| North | 12 | 0.31 |\n",
  "chunks": [
    {
      "text": "...",
      "headingPath": ["Annual Climate Report 2025", "1. Section 1: Regional findings"],
      "pageStart": 1, "pageEnd": 2,
      "charStart": 686, "charEnd": 1364,
      "chunkIndex": 1, "chunkCount": 13, "tokensEstimate": 170
    }
  ],
  "warnings": [],
  "processingMs": 13
}
```

Chunk layout (`outputMode: "chunks"`): each row is `{ "id": "f26767130f-2", "text": "...", "metadata": { source, title, author, language, format, headingPath, chunkIndex, chunkCount, pageStart, pageEnd, charStart, charEnd, tokensEstimate } }`.

A failed document produces `{ "status": "error", "source": {...}, "error": "HTTP 404 Not Found" }`. A `SUMMARY` record in the key-value store gives totals.

### Pricing

Pay per event. You pay for converted documents, not for compute time.

| Event | Price | When it is charged |
|---|---|---|
| Document converted | $0.004 per document | Once per successfully converted document |
| 10 extra pages | $0.002 per block | Once per started block of 10 pages after the first 10 pages of a document |

Examples: a web page or a 10-page PDF costs $0.004, a 50-page PDF $0.012, a 200-page PDF $0.042. Failed, empty or oversized documents are free. Set a maximum cost per run and the Actor stops cleanly when it is reached.

### Limitations (read before you rely on it)

- **No OCR.** Scanned PDFs (images of text) return a warning and no text. OCR engines need several hundred MB of memory and language data downloaded at run time, which would make runs slower and pricier for everyone; it may be added as a separate paid option.
- **Tables are detected by column alignment.** Simple tables are reliable; merged cells, nested tables and tables drawn as images are not. Table rows are not merged across pages.
- **Multi-column PDF layouts** (newspapers, two-column papers) are read line by line across columns, which can interleave text. Single-column documents work best.
- **Headings in PDFs** are inferred from larger font sizes. A PDF whose headings have the same size as the body text, only bold, will not get `#` headings.
- **DOCX page count** comes from the document properties when present, otherwise it is estimated (about 3,000 characters per page); HTML page count is always an estimate (`pagesEstimated: true`). Billing for extra pages uses these values.
- **Images are dropped** (no captions or alt-text extraction for DOCX and PDF).
- **HTML pages that render with JavaScript** are not executed: only the HTML returned by the server is converted. Use a browser-based scraper first if needed.
- Formats: PDF, DOCX, HTML. Legacy `.doc`, `.pptx`, `.xlsx` are not supported.
- Only public URLs or Apify storage are read; the Actor cannot log in to sites.

### Use cases

Feed a knowledge base or RAG pipeline; prepare contracts, reports and papers for LLM summarisation; archive web articles as Markdown; normalise a mixed pile of PDFs and Word files before indexing.

### Call it from code

```js
import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('YOUR_USERNAME/document-to-markdown-converter').call({
    urls: ['https://example.com/report.pdf'],
    outputMode: 'chunks',
    chunkSize: 1200,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
```

### Privacy

Documents are processed inside the Actor run and are not sent to any third-party service. Results stay in your Apify storage under your retention settings.

### Support

Found a document that converts badly? Open an issue on the Actor's Issues tab with the (non-confidential) file or URL and the expected result.

### FAQ

**Does it do OCR on scanned PDFs?** No. It reads the text layer of a PDF. A scanned PDF without a text layer needs an OCR step first (see the OCR Text Extractor in the list below).

**Can I convert files I uploaded?** Yes. Upload files to a key-value store and give their keys and the store ID or name in the input.

**What are chunks for?** With chunking on, each document is cut along headings and paragraphs into overlapping pieces that carry their heading path, ready for embeddings and RAG.

**Are failed documents charged?** No. A failed document returns an item with status "error" and is free.

### More Actors by clearcheck

- [Email Validator](https://apify.com/clearcheck/email-validator)
- [Domain Health Checker](https://apify.com/clearcheck/domain-health-checker)
- [Broken Link Checker and Sitemap SEO Auditor](https://apify.com/clearcheck/link-sitemap-audit)
- [Website Contact Finder](https://apify.com/clearcheck/website-contact-finder)
- [Bulk Phone Number Validator](https://apify.com/clearcheck/phone-validator)
- [Bulk Image Optimizer](https://apify.com/clearcheck/image-optimizer)
- [OCR Text Extractor](https://apify.com/clearcheck/ocr-text-extractor)
- [Dataset Merger and Deduplicator](https://apify.com/clearcheck/dataset-merge-dedupe)
- [Excel and CSV to JSON Converter](https://apify.com/clearcheck/spreadsheet-to-json)

# Actor input Schema

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

Public URLs of PDF, DOCX or HTML documents. The format is detected from the file content, not from the extension.

## `kvStoreKeys` (type: `array`):

Keys of files you uploaded to a key-value store (Console > Storage > Key-value stores > create or open a store > upload records). Set the store ID or name in the field below.

## `kvStoreId` (type: `string`):

ID or name of the key-value store that holds the files listed above. If empty, the run's own default store is used (useful when starting the Actor through the API after seeding it).

## `extractMainContent` (type: `boolean`):

For HTML pages, remove menus, ads, footers and other boilerplate (Readability algorithm). Turn off to convert the whole page.

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

Only convert the first N pages of each PDF. 0 means all pages.

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

Documents larger than this are skipped (and not charged).

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

Password to open protected PDFs (applied to every PDF of the run).

## `enableChunking` (type: `boolean`):

Cut each document into overlapping chunks along headings and paragraphs. Each chunk carries its heading path, page range and character offsets.

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

Maximum size of a chunk in characters (about 4 characters per token, so 1500 is roughly 375 tokens).

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

Characters repeated at the start of the next chunk, to keep context across boundaries. Capped at half the chunk size.

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

'One item per document' returns the full Markdown, metadata and (optionally) the chunks. 'One item per chunk' returns flat {id, text, metadata} rows ready for a vector database or an LLM pipeline (chunking is enabled automatically).

## `saveMarkdownFiles` (type: `boolean`):

Store each converted document as a .md file in the run's key-value store.

## `requestTimeoutSecs` (type: `integer`):

Maximum time to download one URL.

## Actor input object example

```json
{
  "urls": [
    "https://example.com/report.pdf"
  ],
  "kvStoreKeys": [
    "contract.pdf"
  ],
  "extractMainContent": true,
  "maxPagesPerDocument": 0,
  "maxFileSizeMb": 50,
  "enableChunking": false,
  "chunkSize": 1500,
  "chunkOverlap": 200,
  "outputMode": "documents",
  "saveMarkdownFiles": false,
  "requestTimeoutSecs": 60
}
```

# Actor output Schema

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

One dataset item per document (Markdown, metadata, chunks) or per chunk, depending on the chosen layout.

## `markdownFiles` (type: `string`):

The .md files and the SUMMARY record (only filled when 'Also save .md files' is on).

# 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("clearcheck/document-to-markdown-converter").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("clearcheck/document-to-markdown-converter").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 clearcheck/document-to-markdown-converter --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,clearcheck/document-to-markdown-converter"
        }
    }
}
```

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/YVk5wdx8NP6m6XeAU/builds/hdAqpCi0xrcmMf5nr/openapi.json
