npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

md-preview-pdf

v1.1.0

Published

State-of-the-art Markdown to PDF converter with Mermaid diagrams, syntax highlighting, math equations, and more

Readme

MD Preview PDF 📄

A state-of-the-art Markdown to PDF converter that preserves the exact visual appearance of markdown previews, including full support for Mermaid diagrams, syntax highlighting, math equations, and GitHub Flavored Markdown.

License: MIT Node.js Version TypeScript ESLint Tests

✨ Features

  • Full Markdown Support: Complete GFM (GitHub Flavored Markdown) support
  • Mermaid Diagrams: Flowcharts, sequence diagrams, class diagrams, and more
  • Syntax Highlighting: 150+ programming languages with beautiful themes
  • Math Equations: LaTeX math rendering via KaTeX
  • Multiple Themes: GitHub (light/dark), VS Code (light/dark)
  • Table of Contents: Auto-generated TOC with customizable depth
  • Task Lists: Checkbox support for TODO lists
  • Footnotes: Full footnote support
  • Custom Containers: Tips, warnings, info boxes, and more
  • Emoji Support: Convert :emoji: shortcodes to unicode
  • High-Fidelity Output: Uses Puppeteer for pixel-perfect PDF generation

What's new in v1.1.0

  • Render YAML front matter as an HTML table in generated PDFs for clearer metadata presentation
  • Comprehensive security hardening (SRI for CDNs, improved escaping, stricter Mermaid security level)
  • Refactored CSS rendering into dedicated modules for improved maintainability

📦 Installation

From Source (Development)

# Clone the repository
git clone https://github.com/anuragkr29/md-preview-pdf.git
cd md-preview-pdf

# Install dependencies
npm install

# Build the project
npm run build

# Link for global CLI usage (optional)
npm link

From NPM

# Global installation
npm install -g md-preview-pdf

# Local installation
npm install md-preview-pdf

🚀 Quick Start

Command Line

# Basic conversion
md-preview-pdf document.md

# Specify output file
md-preview-pdf document.md output.pdf

# Use dark theme
md-preview-pdf document.md --theme github-dark

# Add page numbers
md-preview-pdf document.md --page-numbers

# Generate table of contents
md-preview-pdf document.md --toc

# TOC with custom depth
md-preview-pdf document.md --toc --toc-depth 2

Note: Table of contents generation requires a ${toc} marker in your markdown file where you want the TOC to appear. Example:

# My Document

${toc}

## Section 1
Content here...

Programmatic Usage

import { Converter, convert } from 'md-preview-pdf';

// Quick convert
const result = await convert('document.md', 'output.pdf', {
  theme: { name: 'github' },
  pdf: { format: 'A4' },
});

// Using the Converter class
const converter = new Converter({
  theme: { name: 'github-dark' },
  toc: true,
  math: true,
});

const result = await converter.convertFile('input.md', 'output.pdf');
console.log(`PDF generated: ${result.outputPath}`);

// Don't forget to cleanup
await converter.cleanup();

📋 CLI Options

| Option | Description | Default | |--------|-------------|---------| | -t, --theme <theme> | Theme (github, github-dark, vscode-light, vscode-dark) | github | | -f, --format <format> | Page format (A4, A3, A5, Letter, Legal, Tabloid) | A4 | | --landscape | Use landscape orientation | false | | --no-background | Disable background printing | true | | -m, --margin <margin> | Page margins (e.g., "20mm" or "10mm,15mm,20mm,15mm") | 20mm | | --toc | Generate table of contents | false | | --toc-depth <depth> | TOC heading depth (1-6) | 3 | | --html | Also output HTML file | false | | --no-math | Disable KaTeX math rendering | true | | --no-emoji | Disable emoji conversion | true | | --no-highlight | Disable syntax highlighting | true | | --mermaid-theme <theme> | Mermaid theme (default, forest, dark, neutral, base) | default | | --header <template> | Custom header HTML template | - | | --footer <template> | Custom footer HTML template | - | | --page-numbers | Add page numbers to footer | false | | --css <path> | Custom CSS file path | - | | --debug | Run in debug mode (show browser) | false | | -v, --verbose | Verbose output | false | | -q, --quiet | Quiet mode | false |

🎨 Themes

List available themes:

md-preview-pdf themes

Available Themes

  • github: GitHub light theme (default)
  • github-dark: GitHub dark theme
  • vscode-light: VS Code light theme
  • vscode-dark: VS Code dark theme

Customizing Theme Styling

Each theme is defined as a CSS string in the src/themes/ directory. Color palettes are split out into src/themes/colors/ as separate modules (for example: github-colors.ts, github-dark-colors.ts, vscode-light-colors.ts, vscode-dark-colors.ts). To customize a theme you can either edit the theme file itself or adjust the palette module it imports.

Tips:

  • Edit src/themes/colors/*-colors.ts to change shared color variables used across themes.
  • Or override CSS variables in your own custom stylesheet and pass it via --css <path>.

To customize a theme:

  1. GitHub Light Theme (src/themes/github.ts)

    • Background color: #ffffff (white)
    • Text color: #24292f (dark gray)
    • Edit the .markdown-body styling and color variables
  2. GitHub Dark Theme (src/themes/github-dark.ts)

    • Background color: #0d1117 (very dark gray)
    • Text color: #c9d1d9 (light gray)
    • Edit the .markdown-body styling and color variables
  3. VS Code Light Theme (src/themes/vscode-light.ts)

    • Background color: #ffffff (white)
    • Text color: #333333 (dark gray)
    • Edit the .markdown-body styling to match VS Code light theme
  4. VS Code Dark Theme (src/themes/vscode-dark.ts)

    • Background color: #1e1e1e (VS Code dark)
    • Text color: #d4d4d4 (light gray)
    • Edit the .markdown-body styling to match VS Code dark theme

To test your theme changes:

npm run build
md-preview-pdf tests/samples/simple-test.md output.pdf --theme github-dark

Sample Output

The following PDFs demonstrate the output quality across all themes:

| Theme | Simple Test | File Size | |-------|-------------|-----------| | GitHub Light | View | 130 KB | | GitHub Dark | View | 130 KB | | VS Code Light | View | 134 KB | | VS Code Dark | View | 134 KB |

📊 Supported Mermaid Diagrams

flowchart TD
    A[Start] --> B{Decision}
    B -->|Yes| C[OK]
    B -->|No| D[End]

Supported diagram types:

  • Flowcharts
  • Sequence diagrams
  • Class diagrams
  • State diagrams
  • Entity Relationship diagrams
  • Gantt charts (full-width rendering)
  • Pie charts
  • Git graphs
  • User Journey diagrams

Mermaid Themes and Configuration

The converter automatically selects the appropriate Mermaid theme based on your document theme:

| Document Theme | Mermaid Theme | |---|---| | github | default | | github-dark | dark | | vscode-light | default | | vscode-dark | dark |

You can also explicitly set the Mermaid theme via CLI:

# Use forest theme
md-preview-pdf document.md --mermaid-theme forest

# Use neutral theme
md-preview-pdf document.md --mermaid-theme neutral

Available Mermaid themes: default, forest, dark, neutral, base

Note: Invalid theme names will trigger a warning and fallback to the default theme automatically.

➗ Math Equations

Inline math with single dollar signs:

The formula $E = mc^2$ is famous.

Block math with double dollar signs:

$$
\int_{a}^{b} f(x) \, dx = F(b) - F(a)
$$

📝 Front Matter

Use YAML front matter to configure document-specific options:

---
title: "My Document"
author: "John Doe"
date: "2024-01-01"
pdfs:
  format: Letter
  margin:
    top: "25mm"
    bottom: "25mm"
---

In v1.1.0 the YAML front matter is also rendered as an HTML table in the generated PDF, providing a clear metadata summary at the top of the document.

📁 Custom Containers

::: tip Pro Tip
This is a helpful tip!
:::

::: warning Warning
Be careful about this!
:::

::: danger Danger
This is critical!
:::

::: info Information
Here's some additional info.
:::

::: details Click to expand
Hidden content here...
:::

🛠️ Development

# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test

# Run in development mode
npm run dev -- input.md

# Lint code
npm run lint

🔧 API Reference

Converter Class

class Converter {
  constructor(options?: ConverterOptions);
  
  // Convert markdown file to PDF
  convertFile(input: string, output?: string): Promise<ConversionResult>;
  
  // Convert markdown string to PDF buffer
  convertString(markdown: string, basePath?: string): Promise<Buffer>;
  
  // Convert multiple files
  convertFiles(inputs: string[], outputDir?: string): Promise<ConversionResult[]>;
  
  // Generate HTML from markdown
  generateHtml(markdown: string, basePath?: string): Promise<string>;
  
  // Parse markdown without rendering
  parseMarkdown(markdown: string): ParsedMarkdown;
  
  // Update options
  setOptions(options: Partial<ConverterOptions>): void;
  
  // Get current options
  getOptions(): ConverterOptions;
  
  // Clean up resources
  cleanup(): Promise<void>;
}

ConverterOptions

interface ConverterOptions {
  pdf?: PDFOptions;           // PDF generation options
  theme?: ThemeOptions;       // Theme configuration
  mermaid?: MermaidOptions;   // Mermaid diagram options
  toc?: boolean;              // Enable table of contents
  tocDepth?: number;          // TOC depth (1-6)
  outputHtml?: boolean;       // Also output HTML
  math?: boolean;             // Enable KaTeX math
  emoji?: boolean;            // Enable emoji conversion
  highlight?: boolean;        // Enable syntax highlighting
  basePath?: string;          // Base path for relative resources
  debug?: boolean;            // Debug mode
}

💻 System Requirements

Minimum Requirements

  • Node.js: >= 18.0.0
  • npm: >= 8.0.0
  • Memory: 512MB minimum (1GB+ recommended for large documents)

Operating System Compatibility

macOS

  • Minimum: macOS 11 (Big Sur) or later
  • Why: Bundled Chromium requires macOS 11+
  • Older Macs: For macOS 10.x, install Google Chrome manually and the tool will automatically use it

Windows

  • Minimum: Windows 10 (version 1809) or later
  • Why: Bundled Chromium requires Windows 10 1809+
  • Older Windows: Install Google Chrome manually for compatibility

Linux

  • Most distributions supported (Ubuntu 18.04+, Debian 10+, Fedora 32+, etc.)
  • Required system packages may vary by distribution
  • See Puppeteer system requirements for details

Browser Requirements

This tool uses Puppeteer which automatically downloads Chromium. However, if the bundled Chromium is incompatible with your system:

  1. Install Google Chrome (recommended): The tool will automatically detect and use it
  2. Set custom Chrome path:
    export PUPPETEER_EXECUTABLE_PATH="/path/to/chrome"

🔧 Troubleshooting

"dyld: cannot load 'Google Chrome for Testing'" (macOS)

Problem: This error occurs on macOS 10.x (Catalina and older) because the bundled Chromium requires macOS 11+.

Solution:

  1. Install Google Chrome from the official website
  2. The tool will automatically detect and use your system Chrome installation
  3. Alternatively, set the Chrome path manually:
    export PUPPETEER_EXECUTABLE_PATH="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    md-preview-pdf document.md

"Failed to launch the browser process" (Windows)

Problem: Bundled Chromium incompatible with older Windows versions.

Solution:

  1. Install Google Chrome
  2. Or set Chrome path:
    set PUPPETEER_EXECUTABLE_PATH="C:\Program Files\Google\Chrome\Application\chrome.exe"
    md-preview-pdf document.md

Out of Memory Errors

Problem: Large documents exhaust available memory.

Solution:

  1. Increase Node.js memory limit:
    export NODE_OPTIONS="--max-old-space-size=4096"
    md-preview-pdf large-document.md
  2. Split large documents into smaller files
  3. Disable resource-intensive features:
    md-preview-pdf document.md --no-highlight --no-math

Slow Performance

Tips:

  • First conversion is slower (Chromium downloads)
  • Use --no-mermaid if you don't have diagrams
  • Disable unused features (--no-math, --no-emoji, --no-highlight)
  • Consider SSD for faster file I/O

Getting Help

  1. Check Puppeteer troubleshooting
  2. Search existing issues
  3. Create a new issue with:
    • Operating system and version
    • Node.js version (node --version)
    • Full error message
    • Command that failed

🧪 Testing

# Run all tests
npm test

# Run tests with coverage
npm test -- --coverage

# Run tests in watch mode
npm test -- --watch

📄 License

MIT License - see LICENSE for details.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

🙏 Acknowledgments


Created by Anurag Kumar

Repository: md-preview-pdf