# Markdown to HTML Converter, Sanitized & Safe (`ucchiii/markdown-to-html`) Actor

Converts Markdown to clean, sanitized HTML: texts, file URLs or Apify dataset columns. GFM tables, task lists, footnotes, code blocks, heading ids, optional table of contents, safe links. Failed documents are free; empty input runs a free demo.

- **URL**: https://apify.com/ucchiii/markdown-to-html.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.70 / 1,000 documents converted

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/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

**Convert Markdown into clean, safe HTML, one row per document** (source, html, title, headings, wordCount, tocHtml, error). Give it Markdown texts, links to .md files or a column of an Apify dataset. Tables, code blocks, task lists and footnotes become HTML; headings get ids; a table of contents is one switch away; scripts and unsafe links are removed. No browser, no LLM, no API key.

**Try it free: leave the input empty and press Start.** The demo converts two sample documents and is not charged (rows carry `_demo: true`). The second sample contains a `<script>` tag and a `javascript:` link, so you can see what the sanitizer does.

### Who this is for

- **You write in Markdown and publish somewhere that wants HTML**: blog posts, help-center articles, release notes, a CMS or a newsletter tool with an HTML box. Convert a whole folder's worth of files in one run instead of pasting them one by one.
- **You have Markdown from a model or from users**: AI answers, comments, support replies, form input. Turning that into HTML and putting it on a page is only safe if the HTML is cleaned first. The sanitizer is on by default.
- **You build pages or documents from a dataset**: another Actor produced a `markdown` column and you need `html` next to it, with a title and a table of contents for each row.

### What you get

| source | title | html (shortened) | wordCount |
|---|---|---|---|
| sample-release-notes.md | Release notes | `<h1 id="release-notes">Release notes</h1>` ... `<table>` ... | 37 |
| sample-untrusted-input.md | Untrusted input | `<p>This text came from a form ...</p>` (no script, no handler) | 27 |
| https://example.com/missing.md | | | 0 (error `http_404`) |

- **GitHub-style Markdown**: tables with alignment, ~~strikethrough~~, task lists (`- [x]`), footnotes (`[^1]`), fenced code blocks with the language kept as `class="language-python"`
- **Heading ids**: every heading gets an id made from its text (`getting-started`; Japanese headings keep their characters; repeated headings get `-1`, `-2`)
- **Table of contents**: a nested list with working links in `tocHtml`, up to the depth you choose, and optionally also placed at the top of `html`
- **Sanitizing (on by default)**: only a safe list of tags, attributes and link types is kept. `<script>`, `<style>`, `<iframe>`, forms, `on...` handlers, `javascript:` and `data:` links are removed
- **Links**: optional `target="_blank"` for external links, and `rel="noopener noreferrer"` (on by default)
- **Row fields**: `title` is the first heading, `headings` lists level, text and id of every heading, `wordCount` counts words (characters for Japanese, Chinese and Korean text)
- Three inputs, mixable in one run: Markdown texts, file URLs, datasets

### Price

**$1.00 per 1,000 documents** ($0.001 per converted document). 1,000 documents cost $1.00, 5,000 cost $5.00.
On the Apify Free plan, the $5 of monthly platform credit covers about 5,000 documents.
Only successful conversions are charged. Failed documents (404, timeout, too large, missing field), empty documents and the demo are free.
Set a maximum cost per run to cap spend: when it is reached the run stops cleanly and does not write the rest. The status message and the STATS record (`stoppedAtChargeLimit: true`) say so. If the maximum is lower than the price of one document, the run fails at the start and nothing is converted or charged.

### Input

```json
{
  "markdownTexts": ["# Hello\n\nThis is **Markdown**."],
  "fileUrls": ["https://example.com/docs/intro.md"],
  "datasetIds": ["WkzbQMuFYuamGv3YF"],
  "markdownField": "markdown",
  "toc": true,
  "tocDepth": 3,
  "sanitize": true,
  "linkTargetBlank": true
}
```

| Field | Default | Meaning |
|---|---|---|
| `markdownTexts` | | Markdown documents, one string each |
| `fileUrls` | | Public links to .md or plain-text files |
| `datasetIds` | | Datasets whose items hold Markdown (a Console dataset URL works too) |
| `markdownField` | `markdown` | Field holding the Markdown in a dataset item (`a.b` for nested) |
| `gfm` | on | Tables, strikethrough, task lists, footnotes |
| `toc` / `tocDepth` / `prependToc` | off / 3 / off | Table of contents, its deepest level, and whether to also put it at the top of the HTML |
| `headingIds` | on | Ids on headings (always on with `toc`) |
| `sanitize` | on | Remove everything unsafe |
| `allowRawHtml` | on | Keep HTML tags written inside the Markdown (safe ones, when sanitizing) |
| `linkTargetBlank` | off | New tab for external links |
| `addNoopener` | on | `rel="noopener noreferrer"` |
| `lineBreaks` | off | A single line break becomes `<br>` |

Leave texts, file URLs and datasets all empty for the free demo.

### Output

One dataset row per document:

```json
{
  "source": "text#0",
  "html": "<h1 id=\"hello\">Hello</h1>\n<p>This is <strong>Markdown</strong>.</p>\n",
  "title": "Hello",
  "headings": [{"level": 1, "text": "Hello", "id": "hello"}],
  "wordCount": 4,
  "tocHtml": "<nav class=\"toc\"><ul><li><a href=\"#hello\">Hello</a></li></ul></nav>",
  "error": null
}
```

`source` is `text#N` (position in your list), the file URL, or `dataset:ID#N` (item number). A failed document has an empty `html` and an `error` such as `http_404`, `timeout`, `blocked_private_address`, `document_too_large`, `empty_document` or `missing_markdown_field: markdown`. A STATS record in the key-value store counts converted, failed (by reason) and charged documents.

### FAQ

**What exactly does sanitizing remove?** Everything outside a safe list. Scripts, styles, iframes, forms, event-handler attributes (`onclick`, `onerror`), `javascript:` and `data:` links, and unknown attributes are dropped. Kept: normal text structure, links (http, https, mailto, tel and relative), images, tables, code, lists, footnotes and task-list checkboxes (always disabled). A Markdown link such as `[x](javascript:...)` is not turned into a link at all; it stays as plain, harmless text. Sanitizing is a safety net for text you did not write yourself. It is not a promise about the content of the links.

**Should I turn sanitizing off?** Only for Markdown you wrote and trust, when you need HTML the safe list does not allow. With it off, the HTML is passed through exactly as written, scripts included. Never turn it off for AI output, comments or any other outside text.

**Which Markdown is supported?** CommonMark plus tables, strikethrough, task lists and footnotes (switch `gfm` off for plain CommonMark). Bare URLs in a sentence are not turned into links automatically: write `[text](url)` or `<url>`. Math, diagrams, emoji shortcodes and syntax highlighting colors are not included; code blocks come out as `<pre><code class="language-...">` for the highlighter of your site.

**How does the table of contents work?** Turn on `toc`. Each row gets `tocHtml`, a nested list of links to the heading ids, down to `tocDepth`. Set `prependToc` to also have it at the top of `html`. Documents without headings get an empty `tocHtml`.

**What are the limits?** 5,000 documents per run and 2 MB per document, fixed and not changeable in the input. A file is downloaded up to 50 MB and then counts as one document (so it must be 2 MB or less). Each URL is fetched with a 30-second timeout and retried up to 3 times on connection errors, timeouts and server errors (not on 404). Links to internal or private addresses are refused. More than 5,000 inputs: the first 5,000 are processed and the run says so.

**What does it cost?** $0.001 per converted document, nothing for failures and the demo. See Price above.

**Which character encodings work for files?** UTF-8 (with or without BOM) first, then the charset the server announces (for example Shift_JIS), otherwise UTF-8 with replacement characters.

**Is my data stored?** No. Texts, files and datasets are read, converted and written to your own run's dataset. Only the URLs you give are fetched, one request per file, and nothing is crawled.

### Notes

Fetch only files you are allowed to read. You are responsible for the rights to the documents you convert and for the sites you point the Actor at.

### More tools from the same developer

- [HTML to Markdown Converter, LLM and RAG](https://apify.com/ucchiii/html-to-markdown) — clean Markdown from URLs, raw HTML or datasets for LLM and RAG
- [DOCX to Markdown](https://apify.com/ucchiii/docx-to-markdown) — Word .docx URLs to Markdown and plain text, with headings and tables
- [RAG Chunker](https://apify.com/ucchiii/rag-chunker) — split scraped pages into chunks for RAG and vector stores
- [HTML to PDF API](https://apify.com/ucchiii/html-to-pdf) — HTML strings or public URLs to PDF: A4 / Letter, margins, header, footer, page numbers
- [Website to Markdown Crawler for RAG and LLMs](https://apify.com/ucchiii/website-markdown-crawler) — crawl a website and get every page as clean Markdown for RAG and LLMs, robots.txt respected, optional chunks

# Actor input Schema

## `markdownTexts` (type: `array`):

Markdown documents to convert, one string per document (up to 2 MB each). Use this when the Markdown is already in your hands, for example from a CMS export or an AI answer. Leave texts, file URLs and datasets all empty for a free demo.

## `fileUrls` (type: `array`):

Public links (http:// or https://) to Markdown or plain-text files, for example a README or a blog post file. Each file is one document (up to 2 MB; the download stops at 50 MB). Failed requests are retried up to 3 times. Internal and private addresses are refused.

## `datasetIds` (type: `array`):

Datasets whose items hold Markdown in the field named below (the 'defaultDatasetId' of a finished run). You can paste a dataset URL from Apify Console too. Every item becomes one document.

## `markdownField` (type: `string`):

Name of the field in each dataset item that holds the Markdown text. Use dots for a nested field, for example 'content.body'.

## `gfm` (type: `boolean`):

Tables, ~~strikethrough~~, task lists (- \[x]) and footnotes (\[^1]). Turn off for plain CommonMark. Bare URLs in the text are not turned into links; write them as [text](url) or <url>.

## `toc` (type: `boolean`):

Adds a nested contents list built from the headings to the 'tocHtml' field of each row. Headings get ids so that the links work.

## `tocDepth` (type: `integer`):

Deepest heading level in the table of contents: 2 means h1 and h2, 3 means h1 to h3. Allowed range 1 to 6 (default 3).

## `prependToc` (type: `boolean`):

Also place the table of contents before the document in the 'html' field. Only has an effect when the table of contents is on and the document has headings.

## `headingIds` (type: `boolean`):

Give every heading an id made from its text (for example 'getting-started', Japanese text is kept) so that pages can link to a section. Repeated headings get -1, -2. Always on when the table of contents is on.

## `sanitize` (type: `boolean`):

Remove everything that could run code or load something unexpected: script and style elements, on\* attributes, javascript: and data: links, forms and iframes. Only a safe list of tags and attributes is kept. Recommended for any text you did not write yourself. Turn off only for Markdown you trust: the HTML is then passed through as written.

## `allowRawHtml` (type: `boolean`):

Keep HTML tags written inside the Markdown (with sanitizing on, only safe tags survive). If off, they are shown as text instead.

## `linkTargetBlank` (type: `boolean`):

Add target="\_blank" to links that point to another site (http, https). Links to sections of the same page are left alone.

## `addNoopener` (type: `boolean`):

Protects your page when a link opens in a new tab. With sanitizing on it is added to every link; with sanitizing off, to external Markdown links.

## `lineBreaks` (type: `boolean`):

Turn a single line break inside a paragraph into <br>, as chat apps do. Off follows the Markdown standard (a line break is a space).

## Actor input object example

```json
{
  "markdownTexts": [
    "# Hello\n\nThis is **Markdown** with a [link](https://example.com), a table and a task list.\n\n| Plan | Price |\n|---|---:|\n| Free | $0 |\n| Pro | $9 |\n\n- [x] Write\n- [ ] Publish\n"
  ],
  "markdownField": "markdown",
  "gfm": true,
  "toc": false,
  "tocDepth": 3,
  "prependToc": false,
  "headingIds": true,
  "sanitize": true,
  "allowRawHtml": true,
  "linkTargetBlank": false,
  "addNoopener": true,
  "lineBreaks": false
}
```

# Actor output Schema

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

One row per document: source, html, title (the first heading), headings, wordCount, tocHtml and error. Download as JSON, CSV, Excel and more.

## `stats` (type: `string`):

Record STATS: documents converted, failed (by reason) and charged, and whether the run stopped at the maximum cost per run.

# 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 = {
    "markdownTexts": [
        "# Hello\n\nThis is **Markdown** with a [link](https://example.com), a table and a task list.\n\n| Plan | Price |\n|---|---:|\n| Free | $0 |\n| Pro | $9 |\n\n- [x] Write\n- [ ] Publish\n"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/markdown-to-html").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 = { "markdownTexts": ["""# Hello

This is **Markdown** with a [link](https://example.com), a table and a task list.

| Plan | Price |
|---|---:|
| Free | $0 |
| Pro | $9 |

- [x] Write
- [ ] Publish
"""] }

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/markdown-to-html").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 '{
  "markdownTexts": [
    "# Hello\\n\\nThis is **Markdown** with a [link](https://example.com), a table and a task list.\\n\\n| Plan | Price |\\n|---|---:|\\n| Free | $0 |\\n| Pro | $9 |\\n\\n- [x] Write\\n- [ ] Publish\\n"
  ]
}' |
apify call ucchiii/markdown-to-html --silent --output-dataset

```

## MCP server setup

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

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/sqsw8NXfLeJdUNJMB/builds/g3ODUzJC81dbxUTSc/openapi.json
