
Markdown to PDF with Node.js: Build a Conversion API
Table of Contents
- What the Markdown to PDF service returns
- How the conversion works
- Convert Markdown to HTML with markdown-it
- Print CSS for Markdown documents
- Code highlighting: highlight.js or Shiki
- Render the PDF with Puppeteer: no scripts, no network
- Add the POST /markdown endpoint
- Turn LLM output into a clean PDF
- Test the service with node –test
- Problems and fixes
- When Pandoc is the better tool
- Before you use it in production
- What the Markdown to PDF service returns
- How the conversion works
- Convert Markdown to HTML with markdown-it
- Print CSS for Markdown documents
- Code highlighting: highlight.js or Shiki
- Render the PDF with Puppeteer: no scripts, no network
- Add the POST /markdown endpoint
- Turn LLM output into a clean PDF
- Test the service with node –test
- Problems and fixes
- When Pandoc is the better tool
- Before you use it in production
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:
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:

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 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:
- markdown-it turns the Markdown into HTML. Raw HTML in the input stays text.
- highlight.js colors the code blocks, and a print stylesheet sets the fonts, the tables and the page breaks.
- Puppeteer starts a headless Chrome that prints the HTML to PDF, with JavaScript and network access off.
Markdown to PDF pipeline:

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, 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:
{
"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:
npm install
Convert Markdown to HTML with markdown-it
Create src/markdown.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 `<span class="image-placeholder">[image: ${md.utils.escapeHtml(alt)}]</span>`;
};
// GitHub tables and chat models use <br> 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(/<br\s*\/?>/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('<p>\\newpage</p>', '<div class="page-break"></div>');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>${md.utils.escapeHtml(title)}</title>
<style>
${css}
</style>
</head>
<body class="break-${breakBefore}">
${body}
</body>
</html>`;
}
html: falsekeeps raw HTML out of the page. Markdown allows raw HTML, so input from a user or a model can contain<script>,<iframe>or<img onerror=...>. With HTML off, markdown-it prints these tags as text. This is the default, and the code sets it so that nobody turns it on by accident.- Links are safe by default. The markdown-it safety notes list the blocked link types:
javascript:,vbscript:,file:, anddata:except GIF, PNG, JPEG and WebP images. - The image rule prints
[image: alt text]for every image that is not adata:image/URL. The render step blocks remote files anyway, and the placeholder is easier to read than an empty image box. - A table cell cannot hold a line break, so people and models write
<br>. With HTML off, the PDF shows the tag as text. Thetable_cell_brrule changes only a<br>inside a table cell into a line break. cleanMarkdown()removes front matter (the---block at the top of many docs) and does not parse it. Before version 5.0.0, the md-to-pdf package parsed front matter with the JavaScript engine of gray-matter on. With such a version, an attacker’s Markdown file can run code on the server (CVE-2021-23639). If you need fields from front matter, use a YAML-only parser.- The text of the first heading goes into
<title>. Chrome writes it into the title field of the PDF, and PDF readers show it in the window title. - A paragraph that contains only
\newpagebecomes a page break. Pandoc Markdown with a LaTeX engine reads the same line as a page break, so one file works with both tools.
Print CSS for Markdown documents
Create src/print.css. markdown.js reads it once at startup and puts it into a <style> tag, together with the GitHub theme of highlight.js:
/* Print styles for Markdown documents.
page.pdf() sets the paper size and the margins. */
html {
font-family: -apple-system, "Segoe UI", "Noto Sans", "Liberation Sans", Arial, sans-serif,
"Apple Color Emoji", "Noto Color Emoji";
font-size: 11pt;
line-height: 1.5;
color: #1f2328;
}
body {
margin: 0;
}
h1, h2, h3, h4 {
line-height: 1.25;
margin: 1.4em 0 0.5em;
break-after: avoid; /* keep a heading on the same page as its text */
}
h1 { font-size: 1.9em; border-bottom: 1px solid #d1d9e0; padding-bottom: 0.2em; }
h2 { font-size: 1.45em; }
h3 { font-size: 1.15em; }
body > :first-child { margin-top: 0; }
p, ul, ol, table, pre, blockquote { margin: 0 0 0.9em; }
p { orphans: 3; widows: 3; }
a { color: #0969da; text-decoration: none; overflow-wrap: anywhere; }
code, pre {
font-family: ui-monospace, Menlo, Consolas, "DejaVu Sans Mono", monospace;
font-size: 0.86em;
}
:not(pre) > code { background: #f6f8fa; padding: 0.1em 0.3em; border-radius: 4px; }
/* Paper cannot scroll, so long code lines wrap. */
pre {
background: #f6f8fa;
border: 1px solid #d1d9e0;
border-radius: 6px;
padding: 0.8em 1em;
white-space: pre-wrap;
overflow-wrap: anywhere;
break-inside: avoid;
}
/* Wide tables shrink to the page width and long words wrap. */
table { width: 100%; border-collapse: collapse; font-size: 0.92em; }
th, td {
border: 1px solid #d1d9e0;
padding: 0.35em 0.6em;
text-align: left;
vertical-align: top;
overflow-wrap: anywhere;
}
th { background: #f6f8fa; }
thead { display: table-header-group; } /* repeat the header row on each page */
tr { break-inside: avoid; }
blockquote { margin-left: 0; padding-left: 1em; border-left: 4px solid #d1d9e0; color: #59636e; }
img { max-width: 100%; break-inside: avoid; }
hr { border: 0; border-top: 1px solid #d1d9e0; margin: 1.5em 0; }
.image-placeholder { color: #59636e; font-style: italic; }
/* Page breaks: the \newpage marker and the breakBefore option. */
.page-break { break-after: page; }
.break-h1 h1,
.break-h2 h1,
.break-h2 h2 { break-before: page; }
.break-h2 h1 + h2 { break-before: auto; } /* no page with only a title */
Paper does not scroll, so most rules wrap content or keep it together. The table shows the results of tests in Chrome 156:
| Rule | What it does |
|---|---|
white-space: pre-wrap and overflow-wrap: anywhere on pre |
Wraps long code lines. Without them, Chrome made all the text on the page smaller and still cut the line off at the right edge. |
overflow-wrap: anywhere on td, th and a |
Wraps long URLs and words, so a table with many columns fits the page width. |
thead { display: table-header-group } |
Repeats the header row on each page. A 90-row table printed the header on all 3 pages. |
break-inside: avoid on tr, pre and img |
Keeps a row, a short code block or an image on one page. A block taller than one page still breaks. |
break-after: avoid on headings |
Moves a heading to the next page together with its text. Without it, a test heading stayed alone at the bottom of page 1. |
"Apple Color Emoji", "Noto Color Emoji" at the end of the font list |
Uses the color emoji font of the system for emoji. |
The breakBefore option adds a class to <body>. With h2, each h1 and h2 starts a new page, except an h2 that comes directly after an h1. Chrome does not add an empty first page when the document starts with such a heading.
Emoji need a color emoji font on the server. macOS has Apple Color Emoji. On Debian or Ubuntu, install Noto Color Emoji. The GitHub Actions runner for Ubuntu 24.04 has it already, but slim Docker images do not:
sudo apt-get install -y fonts-noto-color-emoji
Code highlighting: highlight.js or Shiki
Both libraries work with markdown-it, in different ways:
| highlight.js 11.12 | Shiki 4.6 | |
|---|---|---|
Call from the markdown-it highlight option |
Synchronous, no setup | Create the highlighter at startup (async), then use fromHighlighter, or render with an async plugin |
| HTML output | class="hljs-keyword" and one CSS theme file |
Inline style="color: ..." on each token |
| Grammars | Its own regular expressions | TextMate grammars, as in VS Code |
| Unpacked size on npm | 5.5 MB | 0.6 MB, plus 8.7 MB for @shikijs/langs and 1.5 MB for @shikijs/themes |
This service uses highlight.js. The markdown-it highlight option is synchronous, and highlight.js is synchronous too, so the code needs no startup step. The Shiki markdown-it page says that markdown-it does not support async highlighting. If you want the exact VS Code colors, create the Shiki highlighter at startup and connect it with fromHighlighter from @shikijs/markdown-it/core.
Render the PDF with Puppeteer: no scripts, no network
Create src/render.js:
import puppeteer from 'puppeteer';
// Limits for one render. Change them with environment variables.
const RENDER_TIMEOUT_MS = Number(process.env.RENDER_TIMEOUT_MS ?? 20_000);
const MAX_OPEN_PAGES = Number(process.env.MAX_OPEN_PAGES ?? 4);
let browserPromise;
let openPages = 0;
// One Chrome process for the whole service. If Chrome crashes or cannot
// start, the next request starts a new one.
export function getBrowser() {
browserPromise ??= puppeteer.launch().then(
(browser) => {
browser.on('disconnected', () => {
browserPromise = undefined;
});
return browser;
},
(error) => {
browserPromise = undefined;
throw error;
},
);
return browserPromise;
}
export async function closeBrowser() {
const browser = await browserPromise;
await browser?.close();
}
// Prints one HTML document to PDF and returns the bytes.
export async function renderPdf(html, { format = 'A4' } = {}) {
if (openPages >= MAX_OPEN_PAGES) {
throw Object.assign(new Error('Too many renders. Try again later.'), {
status: 503,
expose: true,
});
}
openPages++;
let page;
try {
const browser = await getBrowser();
page = await browser.newPage();
page.setDefaultTimeout(RENDER_TIMEOUT_MS);
// The document comes from user input. It needs no scripts and no network.
await page.setJavaScriptEnabled(false);
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.url().startsWith('data:')) request.continue();
else request.abort();
});
await page.setContent(html, { waitUntil: 'load' });
return await page.pdf({
format,
margin: { top: '18mm', right: '16mm', bottom: '18mm', left: '16mm' },
printBackground: true, // keep the gray code and table backgrounds
outline: true, // PDF bookmarks from the headings
});
} finally {
openPages--;
// close() fails when Chrome crashed. Keep the first error, not this one.
await page?.close().catch(() => {});
}
}
The browser part is the same as in the HTML to PDF API tutorial, which explains the choices. There is one Chrome for the process and a new page for each request. At most four pages are open, and page.close() runs in finally. Four lines are different here:
page.setJavaScriptEnabled(false)turns off JavaScript. The HTML has no scripts, because markdown-it prints raw HTML as text. With JavaScript off, a future plugin or a bug also cannot run code in Chrome. In a test, a<script>tag in the HTML did not run.- The request handler turns off the network. Server-side request forgery (SSRF) is a request that your server sends for an attacker. A Markdown image such as
makes Chrome load a URL from inside your network. The handler lets onlydata:URLs through and stops all other requests. Puppeteer request interception is the API for this. formatisA4by default. If you do not set it, Puppeteer prints on Letter paper.outline: truewrites the headings as PDF bookmarks. Puppeteer marks this option as experimental. The PDF is also tagged (accessible) by default.
One request to POST /markdown:

Add the POST /markdown endpoint
Create src/app.js:
import express from 'express';
import { markdownToHtml } from './markdown.js';
import { renderPdf } from './render.js';
const FORMATS = ['A4', 'Letter', 'Legal'];
const BREAKS = ['none', 'h1', 'h2'];
// An error that the API returns to the client with this status.
function httpError(status, message) {
return Object.assign(new Error(message), { status, expose: true });
}
// JSON: options in the body. Plain Markdown: options in the query string.
function parseRequest(req) {
let input;
if (req.is('application/json')) input = req.body;
else if (req.is('text/markdown')) input = { ...req.query, markdown: req.body };
else throw httpError(415, 'Send application/json or text/markdown.');
const { markdown, format = 'A4', breakBefore = 'none' } = input ?? {};
if (typeof markdown !== 'string' || markdown.trim() === '') {
throw httpError(400, '"markdown" must be a string that is not empty.');
}
if (!FORMATS.includes(format)) {
throw httpError(400, `"format" must be one of: ${FORMATS.join(', ')}.`);
}
if (!BREAKS.includes(breakBefore)) {
throw httpError(400, `"breakBefore" must be one of: ${BREAKS.join(', ')}.`);
}
return { markdown, format, breakBefore };
}
export function createApp() {
const app = express();
app.disable('x-powered-by');
// 1 MB of Markdown is several hundred pages. A larger body gets status 413.
app.use(express.json({ limit: '1mb' }));
app.use(express.text({ type: 'text/markdown', limit: '1mb' }));
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.post('/markdown', async (req, res) => {
const { markdown, format, breakBefore } = parseRequest(req);
const pdf = await renderPdf(markdownToHtml(markdown, { breakBefore }), { format });
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': 'inline; filename="document.pdf"',
});
res.send(pdf);
});
// Express 5 sends errors from async handlers and from the body parsers here.
app.use((error, req, res, next) => {
if (error.name === 'TimeoutError') {
return res.status(504).json({ error: 'The document did not print in time.' });
}
const status = error.status ?? 500;
if (status >= 500) console.error(error);
res.status(status).json({ error: error.expose ? error.message : 'Rendering failed.' });
});
return app;
}
Apps send JSON with the Markdown and the options. Scripts and curl send the file itself as text/markdown, with the options in the query string. Only the three known fields reach the render step. Never pass request JSON to page.pdf(): its path option writes a file on the server.
| Status | When |
|---|---|
| 200 | The body is a PDF. |
| 400 | markdown is empty, format or breakBefore has an unknown value, or the JSON is not valid. |
| 413 | The body is larger than 1 MB. The error text is request entity too large. |
| 415 | The Content-Type is not application/json or text/markdown. |
| 503 | Four renders are already open. |
| 504 | Chrome did not finish in 20 seconds. |
Create src/server.js. It starts Chrome first, then the HTTP server, and it closes Chrome when the process gets SIGTERM:
import { createApp } from './app.js';
import { closeBrowser, getBrowser } from './render.js';
const port = Number(process.env.PORT ?? 3000);
// Start Chrome first. If it cannot start, the service stops here with the error.
await getBrowser();
const server = createApp().listen(port, (error) => {
if (error) throw error;
console.log(`Markdown to PDF API on http://localhost:${port}`);
});
// Docker and most process managers send SIGTERM before they stop the service.
for (const signal of ['SIGINT', 'SIGTERM']) {
process.once(signal, () => {
server.close(async () => {
await closeBrowser();
process.exit(0);
});
});
}
Start the service:
npm start
Send JSON with options. This request returns two pages, because each h1 starts a new page:
curl -X POST http://localhost:3000/markdown \
-H 'Content-Type: application/json' \
-d '{"markdown": "# Plan\n\nPage one.\n\n# Budget\n\nPage two.", "breakBefore": "h1"}' \
-o plan.pdf
On the Apple M5 Mac, the release notes file took a median of 0.37 seconds over 10 requests. The first request after the start took 0.47 seconds.
Turn LLM output into a clean PDF
Answers from a large language model (LLM) are Markdown too, but LLM output breaks PDF files in ways that docs written by people rarely do:
| Problem in the model output | What the PDF shows without a fix | What this service does |
|---|---|---|
The full answer is inside a code fence marked markdown |
One gray code block with the Markdown source | cleanMarkdown() removes the outer fence |
<br> inside a table cell |
The text <br> in the cell |
The table_cell_br rule makes a line break |
| Very long code lines | Smaller text on the full page, and the end of the line is cut off | white-space: pre-wrap on pre |
| Tables with many columns or long URLs | The same: smaller text and cut-off columns | overflow-wrap: anywhere on the cells |
| Emoji | Missing characters if the server has no emoji font | Install fonts-noto-color-emoji |
Raw HTML such as <b> or <details> |
Text | Keeps it as text on purpose |
| The answer stops inside a code block | The code up to the end: CommonMark closes an open code block at the end of the document | No fix needed |
Math in $...$ or \(...\) |
The TeX source | Not included. Add markdown-it-texmath with KaTeX |
A mermaid code fence |
The diagram source as code | Not included. Render the diagram to an image first |
This is the real output for examples/model-answer.md. The outer fence is gone, the first table cell has two lines, the long Python line wraps, and <b> prints as text:

Also ask the model for clean input. A system prompt can ask for “GitHub Flavored Markdown without HTML tags”. Keep the fixes in the service too, because a model does not always obey its prompt.
Test the service with node –test
Create test/api.test.js. The tests start the app on a free port, send real requests and read each PDF with pdf-lib:
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { after, before, test } from 'node:test';
import { PDFDocument } from 'pdf-lib';
import { createApp } from '../src/app.js';
import { cleanMarkdown, markdownToHtml } from '../src/markdown.js';
import { closeBrowser, renderPdf } from '../src/render.js';
const FENCE = '`'.repeat(3); // a Markdown code fence
let api;
let baseUrl;
before(async () => {
api = createApp().listen(0, '127.0.0.1');
await once(api, 'listening');
baseUrl = `http://127.0.0.1:${api.address().port}`;
});
after(async () => {
api.close();
await closeBrowser();
});
function convert(body, type = 'application/json', query = '') {
return fetch(`${baseUrl}/markdown${query}`, {
method: 'POST',
headers: { 'Content-Type': type },
body: type === 'application/json' ? JSON.stringify(body) : body,
});
}
async function loadPdf(response) {
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-type'), 'application/pdf');
const bytes = new Uint8Array(await response.arrayBuffer());
assert.equal(Buffer.from(bytes.subarray(0, 5)).toString(), '%PDF-');
return PDFDocument.load(bytes);
}
test('JSON body: one page, first heading is the PDF title', async () => {
const pdf = await loadPdf(await convert({ markdown: '# Report\n\nHello **world**.' }));
assert.equal(pdf.getPageCount(), 1);
assert.equal(pdf.getTitle(), 'Report');
});
test('text/markdown body: breakBefore=h1 starts each h1 on a new page', async () => {
const markdown = '# One\n\nA\n\n# Two\n\nB\n\n# Three\n\nC';
const pdf = await loadPdf(await convert(markdown, 'text/markdown', '?breakBefore=h1'));
assert.equal(pdf.getPageCount(), 3);
});
test('\\newpage starts a new page', async () => {
const pdf = await loadPdf(await convert({ markdown: 'Page one\n\n\\newpage\n\nPage two' }));
assert.equal(pdf.getPageCount(), 2);
});
test('raw HTML and javascript: links are printed as text', () => {
const html = markdownToHtml('<script>alert(1)</script>\n\n[click](javascript:alert(1))');
assert.match(html, /<script>alert\(1\)<\/script>/);
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('<br> breaks a line in a table cell, nowhere else', () => {
const html = markdownToHtml('| A |\n|---|\n| one<br>two |\n\nText <br> here');
assert.match(html, /one<br>\ntwo/);
assert.match(html, /Text <br> 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: `` }));
// An <img> tag in the HTML: only the request filter in render.js stops it.
await renderPdf(`<img src="${url}">`);
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:
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 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. 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. |
<b>, <br> or <details> 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 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 says that PDF engines add risks that --sandbox does not stop. |
Pandoc or this service:

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:
- Put it in a container. The HTML to PDF API tutorial has a tested Dockerfile. Add
fonts-noto-color-emojiand the fonts that your documents use. - Add page numbers if your documents need them. Puppeteer prints them with
displayHeaderFooterand afooterTemplate. - 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.
- Cache the output. The same Markdown and options give the same PDF, so you can store each PDF under a hash of its input.
- 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 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.