Markdown to PDF with Code Highlighting: How to Preserve Syntax Colors
To keep syntax colors when converting Markdown to PDF, test the whole rendering path—not just the Markdown source. A fenced code block needs a language identifier, the renderer needs a syntax highlighter, and the PDF export needs to preserve backgrounds, fonts, and wrapping.
For a one-off document, MarkdownToImage's Markdown to PDF tool is the shortest route: paste or upload Markdown, check the preview, choose a theme and document width, then export. For automated or highly customized builds, use md-to-pdf, VS Code Markdown PDF, or Pandoc with explicit highlighting settings.
Most failures are reproducible. Start with these three checks:
- The code fence has no language identifier. A block opened with three backticks alone is only preformatted text. Use
javascript,python,bash, or the closest supported language after the opening fence. - Background graphics are disabled. Syntax themes often rely on both foreground colors and a code-block background. A browser or Chromium export can keep the tokens but drop the background when print backgrounds are disabled.
- Preview and PDF use different rendering settings. A different renderer, theme, font, page width, or print stylesheet can change token colors and line wrapping. Compare the exported PDF with a small known sample before processing a long document.
This diagnosis is more useful than blaming “PDF” as a format. PDF can preserve colored text perfectly; the question is what the export pipeline rendered before writing the file.
Paste this block into the same document and export it before you convert the full report:
const palette = ["cyan", "amber", "coral"];
function renderStatus(format) {
return `${format}: ${palette.length} colors`;
}
console.log(renderStatus("PDF"));
Check five details in both preview and PDF: keyword color, string color, code-block background, monospace font, and wrapping on the template-literal line. If one changes, fix the theme or export settings before moving on.
The web tool renders PDFs in a server-side Chromium runtime. It supports syntax-highlighted code blocks, KaTeX formulas, Mermaid diagrams, tables, embedded images, and task lists. The preview is the reference: set the theme, font, and document width there, then export and compare the test block.
Current free exports include a watermark. A signed-in free account receives five total watermark-free exports; pricing and quotas can change, so check the current converter page before planning a recurring workflow.
This path is best when you want a polished result without installing a local tool.
md-to-pdf converts Markdown with Marked, highlights code with highlight.js, and generates the PDF through Puppeteer/Chromium. Its default highlighting style is GitHub; you can choose another style explicitly.
md-to-pdf input.md --highlight-style github --pdf-options '{ "printBackground": true }'
Use the CLI when the same document must be rebuilt in a script or CI job. If a dark highlight style has a background color, keep printBackground enabled. Do not process untrusted Markdown without sanitizing it; the tool's own documentation calls this out as a security consideration.
The Markdown PDF extension exports through a Chromium-based browser and uses highlight.js for fenced code blocks. Syntax highlighting is enabled by default, and its theme is configured independently with markdown-pdf.highlightStyle.
"markdown-pdf.highlightStyle": "github.css"
After changing the setting, export the small test block again. The extension currently uses highlight.js v11, so an old theme filename may be renamed or unavailable. Choose a current style instead of assuming a legacy name still works.
Pandoc uses Skylighting for fenced code blocks that specify a language. Current Pandoc versions support --syntax-highlighting; the older --highlight-style spelling is deprecated.
pandoc input.md -o output.pdf --syntax-highlighting=pygments
Pandoc also supports built-in styles such as kate, tango, zenburn, and breezeDark, plus custom JSON .theme files. It is the strongest option when you already use Pandoc templates, citations, or a LaTeX-based publishing workflow. Test fonts and page breaks separately because the PDF engine and template still affect the final layout.
Printing an already rendered Markdown page to PDF can work, but the result depends on that page's print CSS. Some sites preserve syntax colors and backgrounds; others simplify everything for paper. Enable background graphics in the print dialog, inspect page breaks, and compare the test block before relying on this method.
Browser print is useful for a page that already looks correct. It is not a reproducible build pipeline unless you also control the HTML, CSS, browser version, and print settings.
- Add a language identifier to every fenced code block.
- Prefer a light, high-contrast theme for documents that may be printed.
- Enable background graphics when the chosen theme needs them.
- Use a known monospace font and confirm that it is available in the export environment.
- Check long lines at the final page width; do not assume screen wrapping matches A4 or Letter.
- Export the small JavaScript sample before a long report.
- Sanitize Markdown from users or external systems before feeding it to a local converter.
- Open the final PDF once and verify colors, selectable text, links, images, and page breaks.
For a wider tool comparison, see five ways to convert Markdown to PDF. For repeatable builds, continue with batch conversion using CLI, Pandoc, and CI.
Why is the code colored in preview but plain in the PDF?
First enable background graphics. Then check whether the export uses the same theme and renderer as the preview. A print stylesheet can also override token colors.
Which theme should I use for a printable PDF?
Start with GitHub or another light theme. It usually remains readable in color and grayscale. Dark themes can work for screen-only PDFs, but verify backgrounds and contrast before sharing.
Can I keep line numbers?
Only if the chosen renderer and theme add them. Line numbers are not part of standard fenced Markdown. For deterministic results, use a CLI or stylesheet you control and test the page width.
Can I batch-convert files without losing highlighting?
Yes. Use a Chromium-based CLI for consistent web-style highlighting or Pandoc with an explicit syntax theme. Pin the tool version and theme in CI so future builds do not change unexpectedly.
Open MarkdownToImage's Markdown to PDF converter, paste the small JavaScript block from this guide, and export one PDF. Compare the preview and file side by side. Once the colors, background, font, and wrapping match, replace the sample with your real document.