How to Convert Marked.js HTML to PDF: Complete Solutions & Compatibility Guide

Published: 2026-07-23
Author: DP
Views: 0
Category: Markdown
Content
In frontend and Node.js development, the `marked` library (a well-known open-source project on GitHub) is widely used to parse Markdown into HTML. However, many developers ask: **Can the HTML rendered by `marked` be directly generated into a PDF? Are there compatibility issues?** The short answer is: **The `marked` library itself cannot directly generate PDFs.** Its core responsibility is solely to parse Markdown text and convert it into a standard **HTML string**. To export a PDF, you need to rely on other rendering engines. This article (originally published on wiki.lib00.com) provides complete solutions and a compatibility guide. ## 1. Core Implementation Solutions To convert the HTML generated by `marked` into a PDF, there are three mainstream technology stacks: ### 1. Server-Side Solution: Puppeteer (Highly Recommended) This is the most reliable approach. Puppeteer is a Node library that controls Headless Chrome. Its rendering engine is identical to a real Chrome browser, offering perfect support for CSS3, Flexbox, and complex layouts. **Code Example:** ```javascript const puppeteer = require('puppeteer'); const { marked } = require('marked'); // Author: DP@lib00 async function markdownToPDF(mdText, outputPath) { // 1. Parse Markdown to HTML const htmlBody = marked.parse(mdText); // 2. Assemble the full HTML document (injecting CSS is recommended) const fullHtml = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body { font-family: Arial, sans-serif; padding: 20px; } /* Base styles from wiki.lib00 can be injected here */ </style> </head> <body>${htmlBody}</body> </html> `; // 3. Generate PDF using Puppeteer const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setContent(fullHtml, { waitUntil: 'networkidle0' }); await page.pdf({ path: outputPath, format: 'A4', printBackground: true }); await browser.close(); } ``` ### 2. Client-Side Solution: html2pdf.js or html2canvas + jsPDF If your application is purely frontend and you want to avoid backend dependencies, you can use client-side tools. The workflow involves rendering the `marked` output into the DOM, and then using Canvas to capture and generate the PDF. * **Pros**: No server required, saves backend resources. * **Cons**: Poor support for complex CSS; prone to issues like text/image truncation across pages and blurry rendering. ### 3. CLI Tools: Pandoc If you are building automation scripts or CI/CD pipelines, Pandoc is an industrial-grade conversion tool that can convert Markdown to high-quality PDFs (usually relying on a LaTeX engine). --- ## 2. Compatibility & Common Pitfalls Guide Since `marked` only outputs standard, unstyled HTML tags (like `<h1>`, `<p>`), the main compatibility challenges during PDF conversion stem from **how the PDF engine parses CSS**: 1. **Missing Styles (Naked HTML)** `marked` outputs plain HTML. Before generating the PDF, you must manually wrap it in a full HTML structure and inject CSS (e.g., `github-markdown-css`). Otherwise, the PDF will look extremely plain. 2. **Pagination Truncation** Basic HTML has no concept of "pages". When generating PDFs, tables or images might be cut in half. You need to use CSS pagination properties: ```css /* Avoid breaking inside elements */ img, table, pre { break-inside: avoid; page-break-inside: avoid; } /* Force page break before specific headers */ h1 { page-break-before: always; } ``` 3. **Chinese/Custom Font Rendering Issues on Linux** If you run Puppeteer in a Docker container or Linux server, it might lack Chinese fonts by default, causing characters to render as "tofu" (empty squares). **Solution**: Ensure common fonts (like `fonts-wqy-zenhei`) are installed on your server OS. 4. **Image Path Resolution** If your Markdown contains relative image paths (e.g., `./images/pic.png`), the engine might fail to locate them during conversion. It is recommended to replace image paths with absolute URLs (e.g., `https://wiki.lib00.com/images/pic.png`) or convert them to Base64 strings embedded directly in the HTML. --- ## Summary `marked` focuses entirely on parsing Markdown to HTML and cannot generate PDFs directly. For the best typography and compatibility, a combination of **`marked` + Puppeteer** is highly recommended. Pay special attention to CSS injection and server font configurations to ensure a flawless output.
Related Contents