# Markdown to PDF with Node.js: Build a Conversion API

> Convert Markdown to PDF with Node.js: a tested API with markdown-it, highlight.js, print CSS and Puppeteer that is safe for user and AI model input.

## What the Markdown to PDF service returns

Your app writes Markdown: release notes, runbooks, reports or answers from an AI model. Your users want a PDF that they can file or send. The service that you build here converts Markdown to PDF over HTTP with Node.js. It prints code in color, fits wide tables and long lines on the page, and keeps raw HTML and remote files out of the render.

Start the service, then send a Markdown (`.md`) file:

```bash
curl -X POST http://localhost:3000/markdown \
-H 'Content-Type: text/markdown' \
--data-binary @examples/release-notes.md \
-o release-notes.pdf
```

The response is a one-page A4 PDF. This is page 1 of the real output:

![Page 1 of the PDF made from the release notes Markdown file, with a table, colored code blocks, a quote and emoji](/assets/en/blog/markdown-to-pdf-api/markdown-to-pdf-release-notes.webp)

The heading, the table, both code blocks and the emoji come from the example file. The first heading is also the PDF title, and each heading is a PDF bookmark.

| Tested with | Version |
|---|---|
| Node.js | 22.22.3 on macOS, 22.23.4 in GitHub Actions |
| Puppeteer | 25.16.0 with Chrome 156.0.8078.47 |
| markdown-it | 15.0.3 |
| highlight.js | 11.12.0 |
| Express | 5.3.0 |
| pdf-lib (tests only) | 1.17.1 |
| Operating systems | macOS 26.7.1 on Apple Silicon (M5), Ubuntu 24.04 in GitHub Actions |
| Test date | 9 November 2026 |

The complete code, the example files and the CI script are in the [nodejs-puppeteer folder](https://github.com/apisk-com/markdown-to-pdf/tree/main/nodejs-puppeteer) of the markdown-to-pdf repository.

## How the conversion works

Chrome cannot read Markdown. To convert Markdown to PDF, the service turns the text into HTML first and then prints that HTML:

1. markdown-it turns the Markdown into HTML. Raw HTML in the input stays text.
2. highlight.js colors the code blocks, and a print stylesheet sets the fonts, the tables and the page breaks.
3. Puppeteer starts a headless Chrome that prints the HTML to PDF, with JavaScript and network access off.

Markdown to PDF pipeline:

![Flow from Markdown text through markdown-it with HTML off and an HTML page with print CSS to Chrome and a PDF file](/assets/en/blog/markdown-to-pdf-api/diagram_markdown-text-markdown.png)

markdown-it follows CommonMark (the common Markdown specification) and adds GitHub-style tables. It keeps HTML input off by default, and small plugins can change its token list. The marked parser is also popular, but [marked does not sanitize the output HTML](https://marked.js.org/), so untrusted input needs one more step.

Create a folder for the Markdown to PDF project and a `package.json` file. The versions are exact, so `npm ci` installs the same code that the tests used:

```json
{
"name": "markdown-to-pdf-api",
"version": "1.0.0",
"description": "A small Markdown to PDF API with Express 5, markdown-it, highlight.js and Puppeteer.",
"private": true,
"type": "module",
"license": "MIT",
"engines": {
"node": ">=22.12.0"
},
"scripts": {
"start": "node src/server.js",
"test": "node --test"
},
"dependencies": {
"express": "5.3.0",
"highlight.js": "11.12.0",
"markdown-it": "15.0.3",
"puppeteer": "25.16.0"
},
"devDependencies": {
"pdf-lib": "1.17.1"
}
}
```

Install the packages. Puppeteer downloads its own Chrome during the install, and version 25 needs Node.js 22.12 or later:

```bash
npm install
```

## Convert Markdown to HTML with markdown-it

Create `src/markdown.js`:

```js
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';

const require = createRequire(import.meta.url);

// The print stylesheet and a highlight.js color theme, read once at startup.
const css = [
readFileSync(new URL('./print.css', import.meta.url), 'utf8'),
readFileSync(require.resolve('highlight.js/styles/github.css'), 'utf8'),
].join('\n');

const md = new MarkdownIt({
html: false, // raw HTML in the Markdown is printed as text, never rendered
linkify: true, // bare URLs become links
highlight(code, lang) {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
}
return ''; // unknown language: markdown-it escapes the code as plain text
},
});

// The PDF step loads no remote files. Print the alt text instead of the image.
const renderImage = md.renderer.rules.image;
md.renderer.rules.image = (tokens, idx, options, env, self) => {
const src = tokens[idx].attrGet('src') ?? '';
if (src.startsWith('data:image/')) return renderImage(tokens, idx, options, env, self);
const alt = self.renderInlineAsText(tokens[idx].children, options, env);
return ` [image: ${md.utils.escapeHtml(alt)}] `;
};

// GitHub tables and chat models use
for a line break in a table cell.
// HTML is off, so change only this one tag into a line break.
md.core.ruler.push('table_cell_br', (state) => {
let inCell = false;
for (const token of state.tokens) {
if (token.type === 'th_open' || token.type === 'td_open') inCell = true;
if (token.type === 'th_close' || token.type === 'td_close') inCell = false;
if (!inCell || token.type !== 'inline') continue;
token.children = token.children.flatMap((child) => {
if (child.type !== 'text') return [child];
return child.content.split(/ /i).flatMap((part, i) => {
const text = new state.Token('text', '', 0);
text.content = part;
return i === 0 ? [text] : [new state.Token('hardbreak', 'br', 0), text];
});
});
}
});

// Clean the input before markdown-it reads it.
export function cleanMarkdown(text) {
let clean = text.replace(/\r\n?/g, '\n').trim();
// Front matter (--- at the top) is metadata, not text. Remove it without
// parsing it: some front matter parsers can run JavaScript.
clean = clean.replace(/^---[a-z]*\n[\s\S]*?\n---(\n|$)/, '');
// Chat models often put the full answer in a code fence marked markdown.
// Remove that outer fence, so the answer prints as a document, not as code.
const fenced = clean.match(/^(`{3,}|~{3,})(?:markdown|md)[ \t]*\n([\s\S]*?)\n\1[ \t]*$/i);
return fenced ? fenced[2] : clean;
}

function firstHeadingText(tokens) {
const i = tokens.findIndex((token) => token.type === 'heading_open');
if (i === -1) return '';
return tokens[i + 1].children
.filter((child) => child.type === 'text' || child.type === 'code_inline')
.map((child) => child.content)
.join('');
}

// Markdown in, a complete HTML document out. breakBefore: 'none', 'h1' or 'h2'.
export function markdownToHtml(markdown, { breakBefore = 'none' } = {}) {
const tokens = md.parse(cleanMarkdown(markdown), {});
const title = firstHeadingText(tokens) || 'Document';
const body = md.renderer
.render(tokens, md.options, {})
// A paragraph with only \newpage starts a new page, as in Pandoc with LaTeX.
.replaceAll(' \\newpage
', '
');

return `

${md.utils.escapeHtml(title)}

${body}

`;
}
```

- `html: false` keeps raw HTML out of the page. Markdown allows raw HTML, so input from a user or a model can contain ` \n\n[click](javascript:alert(1))');
assert.match(html, / alert\(1\) /);
assert.doesNotMatch(html, /href="javascript:/);
});

test('code fences get highlight.js classes', () => {
assert.match(markdownToHtml(`${FENCE}js\nconst a = 1;\n${FENCE}`), /hljs-keyword/);
});

test('
breaks a line in a table cell, nowhere else', () => {
const html = markdownToHtml('| A |\n|---|\n| one
two |\n\nText
here');
assert.match(html, /one
\ntwo/);
assert.match(html, /Text
here/);
});

test('front matter and an outer markdown fence are removed', () => {
assert.equal(cleanMarkdown('---\ntitle: Notes\n---\n# Hi'), '# Hi');
assert.equal(cleanMarkdown(`${FENCE}markdown\n# Hi\n\nText\n${FENCE}`), '# Hi\n\nText');
const code = `${FENCE}js\nx = 1\n${FENCE}`;
assert.equal(cleanMarkdown(code), code);
});

test('the render makes no network requests', async () => {
let hits = 0;
const target = createServer((req, res) => {
hits += 1;
res.end();
});
target.listen(0, '127.0.0.1');
await once(target, 'listening');
const url = `http://127.0.0.1:${target.address().port}/secret.png`;

// A Markdown image prints its alt text.
await loadPdf(await convert({ markdown: `![secret](${url})` }));
// An tag in the HTML: only the request filter in render.js stops it.
await renderPdf(` `);

target.close();
assert.equal(hits, 0);
});

test('bad input gets 400, 413 and 415', async () => {
assert.equal((await convert({ markdown: ' ' })).status, 400);
assert.equal((await convert({ markdown: '# A', format: 'A5' })).status, 400);
assert.equal((await convert('# A', 'text/markdown', '?breakBefore=h3')).status, 400);
assert.equal((await convert({ markdown: 'x'.repeat(1_100_000) })).status, 413);
assert.equal((await convert('# A', 'text/plain')).status, 415);
});
```

Keep the network test when you change the code. A local HTTP server counts the requests that reach it. Without the request handler in `render.js`, the count was 1 and the test failed. Run the tests:

```bash
npm test
```

All 9 tests pass in about 2 seconds on the Mac. In GitHub Actions, `test.sh` also installs the emoji font, starts the server and converts both example files with curl.

> Chrome, fonts and print CSS need updates on each server. If you do not want that work, the APISK [HTML to PDF API](https://docs.google.com/forms/d/e/1FAIpQLSehVgyeBPWdAuQeVinkCWb0e17QmZ8GpYhARgFHkx2N30rvRA/viewform?usp=pp_url&entry.2061938923=HTML%20to%20PDF%20API%20-%20convert%20url%2C%20html%2C%20markdown%20to%20pdf) converts Markdown, HTML or a URL to PDF as a hosted service. It is in early access.

## Problems and fixes

| What you see | Cause | Fix |
|---|---|---|
| `Error: Could not find Chrome (ver. 156.0.8078.47). This can occur if either...` | The install did not download Chrome, or the cache folder is different for the user that runs the service | Run `npx puppeteer browsers install chrome` as that user. |
| `No usable sandbox!` when Chrome starts on Ubuntu 23.10 or later | AppArmor blocks the user namespaces that the Chrome sandbox uses | Follow the [Chromium AppArmor notes](https://chromium.googlesource.com/chromium/src/+/main/docs/security/apparmor-userns-restrictions.md). Do not turn off the sandbox for untrusted input. |
| The PDF is Letter size, not A4 | The Puppeteer default `format` is `letter` | Set `format`. This service uses `A4` by default. |
| `[image: ...]` instead of an image | The service does not load remote files | Embed the image as a `data:image/png;base64,...` URL. |
| ` `, `
` or ` ` print as text | `html: false` in markdown-it | This is correct for untrusted input. For trusted input only, set `html: true` and sanitize the HTML. |
| Fonts look different on macOS and Linux | Each system has other fonts | Install the same font files on every server, or embed them with `@font-face` and a `data:` URL. |

## When Pandoc is the better tool

[Pandoc](https://pandoc.org/MANUAL.html) also converts Markdown to PDF, as a command-line tool. By default it uses LaTeX (`pdflatex`). With `--pdf-engine` it can also go through HTML with WeasyPrint, or use Typst. Pick the tool by the job:

| Job | Better tool | Reason |
|---|---|---|
| Math, citations and cross-references | Pandoc with LaTeX | Pandoc reads TeX math and citation keys, and LaTeX typesets them. |
| DOCX, EPUB and PDF from the same file | Pandoc | One converter writes all these formats. |
| The same CSS as your website or app | This service | Chrome prints the CSS that you already have. |
| Emoji and mixed scripts with system fonts | This service | Chrome uses the installed fonts. With LaTeX, you configure the fonts for `xelatex` or `lualatex`. |
| Untrusted input over HTTP | This service | The [Pandoc security note](https://pandoc.org/MANUAL.html#a-note-on-security) says that PDF engines add risks that `--sandbox` does not stop. |

Pandoc or this service:

![Decision: untrusted input goes to the Chrome service, math, citations or DOCX go to Pandoc with LaTeX, other jobs to the Chrome service](/assets/en/blog/markdown-to-pdf-api/diagram_untrusted-input-chrome.png)

## Before you use it in production

The Markdown to PDF service in the repository works as it is. Add these parts before real users send documents:

1. Put it in a container. The [HTML to PDF API tutorial](/blog/html-to-pdf-api-nodejs/) has a tested Dockerfile. Add `fonts-noto-color-emoji` and the fonts that your documents use.
2. Add page numbers if your documents need them. Puppeteer prints them with `displayHeaderFooter` and a `footerTemplate`.
3. If your documents need remote images, allow only one asset host that you control. In the request handler, make sure that each URL goes to that host. Also protect the service against SSRF: private IP addresses, redirects and DNS rebinding.
4. Cache the output. The same Markdown and options give the same PDF, so you can store each PDF under a hash of its input.
5. Tune the limits for your documents: 1 MB per body, 20 seconds per render and four open pages are values to start with.

The code for each step of this tutorial is in the [nodejs-puppeteer folder](https://github.com/apisk-com/markdown-to-pdf/tree/main/nodejs-puppeteer) of the markdown-to-pdf repository.

## Frequently Asked Questions

### How do I convert Markdown to PDF in Node.js without Puppeteer?

You need another layout engine. Call Pandoc from Node.js with a LaTeX or Typst PDF engine, or send the HTML from markdown-it to WeasyPrint. PDF libraries such as PDFKit and pdfmake draw pages from code, but they do not read Markdown. With them, you map each Markdown element to drawing calls yourself.

### How do I convert an .md file to PDF from the command line?

With this service on port 3000, send the file with curl: `curl -X POST http://localhost:3000/markdown -H 'Content-Type: text/markdown' --data-binary @notes.md -o notes.pdf`. Without a server, `pandoc notes.md -o notes.pdf` also works, but Pandoc needs a LaTeX engine for this default route.

### Why does my Markdown PDF show HTML tags as text?

The Markdown parser has HTML input turned off. markdown-it does this by default, and it is the safe setting for Markdown from users or AI models. This service changes `<br>` in table cells into line breaks and prints all other tags as text. For trusted input only, set `html: true` and send the HTML through a sanitizer.

### How do I add a page break in Markdown for PDF output?

Markdown has no page break syntax, so the break comes from CSS. In this service, a paragraph with only `\newpage` starts a new page, and `"breakBefore": "h2"` starts a page before each `h1` and `h2`. In your own HTML, put `break-before: page` on the element that must start a page.

### Why is a code block cut off at the right edge of the PDF?

A code block keeps its line breaks, and paper cannot scroll. In a test with Chrome 156, a long line made all the text on the page smaller and was still cut off. Add `white-space: pre-wrap` and `overflow-wrap: anywhere` to `pre` in the print CSS, so that long lines wrap.

### Can I convert Markdown with Mermaid diagrams to PDF?

Not with this service as it is. JavaScript is off in Chrome, so a `mermaid` code fence prints as code. Render each diagram to PNG first, for example with `mmdc` from `@mermaid-js/mermaid-cli`, and put the PNG into the Markdown as a `data:image/png` URL. If you turn on JavaScript for Mermaid instead, untrusted input can also run code.

---

[View the canonical page](https://apisk.com/blog/markdown-to-pdf-api/) · [Browse llms.txt](https://apisk.com/llms.txt)
