Markdown to PDF (with Mermaid & Math)
📑 Table of Contents
🚀 Overview
Markdown to PDF (with Mermaid & Math) is a modern, 100% offline and local-first Visual Studio Code extension engineered to convert your Markdown (.md) documents into print-ready, publication-grade PDF files.
Traditional markdown-to-PDF solutions often suffer from critical issues:
- They require downloading heavy headless browser binaries (Puppeteer / Chromium > 300MB) that fail in restricted enterprise environments.
- They fail to render or mangle Mermaid diagrams (cut-off boundaries, distorted fonts, dark theme glitches).
- They lack native support for KaTeX LaTeX math equations or corrupt math formulas during HTML parsing.
- They break pages mid-heading (orphan headers) or fail to resolve relative image paths.
Markdown to PDF solves all of these problems with a bundled client-side rendering pipeline powered by Mermaid 11, KaTeX, Marked, DOMPurify, and jsPDF—giving you pixel-perfect, crisp vector documents without external dependencies.
✨ Key Features
- 📊 High-DPI Mermaid Diagram Engine: Pre-renders SVGs at 2x/3x Retina resolution to crisp PNG vector assets with light background isolation before document assembly.
- 📐 Comprehensive KaTeX LaTeX Math: Beautiful rendering of inline formulas (
$E=mc^2$) and multiline block matrices/equations ($$\int_a^b f(x)dx$$).
- 🛡️ Code Block Shielding: Mathematical dollar signs (
$) inside inline code (`let $var = 1`) or fenced code blocks (```) are safely shielded and never corrupted.
- 🖼️ Automatic Base64 Image Inlining: Scans relative and local image paths (
./images/flow.png, ../assets/logo.svg, etc.) and embeds them directly as Base64 data URIs.
- 📄 Smart Anti-Orphan Pagination: Calculates page layout dynamically, keeping section headings (
h1–h6) bound to their child content and preventing awkward page breaks.
- 🎨 5 Built-in Mermaid Themes: Choose from
default, neutral, dark, forest, and base themes to match your preferred aesthetic.
- 📐 Flexible Page Geometry: Configure A4, Letter, or Legal formats in portrait or landscape orientations with customizable margin padding.
- 🔒 100% Private & Offline: Zero external network calls, zero analytics/telemetry, and strict Content Security Policy (CSP) enforcement.
- ⚡ Fast 1-Click Export: Trigger from the editor title bar, editor context menu, explorer context menu, or Command Palette.
🎯 Quick Start Guide
Step 1: Open or Create a Markdown Document
Create a .md file with Markdown text, tables, math equations, and Mermaid diagrams:
# High-Performance API Gateway
This document outlines the distributed architecture and routing metrics.
## Architecture Flow
```mermaid
flowchart TD
Client[Client App] -->|HTTPS| Gateway[API Gateway]
Gateway --> Auth[Auth Service]
Gateway --> Orders[Order Processing]
Orders --> DB[(PostgreSQL)]
```
## Latency SLA Calculation
The allowable tail latency bounds are governed by:
$$L_{\text{total}} = L_{\text{gateway}} + \max(L_{\text{auth}}, L_{\text{orders}}) + \epsilon$$
Where inline jitter satisfies $\epsilon \le 2.5\text{ms}$.
Step 2: Trigger the PDF Export
You have three intuitive ways to export:
- Editor Title Bar: Click the PDF icon (
$(file-pdf)) in the top-right corner of the editor.
- Right-Click Context Menu: Right-click anywhere in the editor or on a
.md file in the Explorer and choose Export Markdown as PDF.
- Command Palette: Press
Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS) and run Export Markdown as PDF.
Step 3: Save and Open
- Choose your destination file path in the save dialog and click Save.
- A progress indicator will display live rendering status.
- Upon completion, click
Open PDF in the notification banner to view your document immediately.
📊 Supported Mermaid Diagram Types
The extension bundles Mermaid v11.16.1, supporting all modern diagram syntax inside standard ```mermaid fences:
1. Flowcharts (flowchart / graph)
```mermaid
flowchart LR
Start([Request Received]) --> Validate{Valid Token?}
Validate -- Yes --> Process[Execute Query]
Validate -- No --> Reject[Return 401 Unauthorized]
Process --> Cache[(Redis Cache)]
Process --> Respond([HTTP 200 OK])
```
2. Sequence Diagrams (sequenceDiagram)
```mermaid
sequenceDiagram
autonumber
actor User
participant App as Web App
participant API as API Server
participant DB as Database
User->>App: Click Checkout
App->>API: POST /api/checkout
API->>DB: Deduct Inventory & Create Order
DB-->>API: Transaction Committed
API-->>App: 201 Created
App-->>User: Show Confirmation Screen
```
3. Class Diagrams (classDiagram)
```mermaid
classDiagram
class Vehicle {
+String make
+String model
+int year
+startEngine() void
}
class ElectricCar {
+int batteryCapacity
+chargeBattery() void
}
Vehicle <|-- ElectricCar
```
4. State Diagrams (stateDiagram-v2)
```mermaid
stateDiagram-v2
[*] --> Idle
Idle --> Processing : Submit Task
Processing --> Succeeded : Complete
Processing --> Failed : Exception
Failed --> Retrying : Retry Count < 3
Retrying --> Processing : Attempt
Failed --> [*] : Terminated
Succeeded --> [*]
```
5. Entity Relationship Diagrams (erDiagram)
```mermaid
erDiagram
USER ||--o{ ORDER : places
ORDER ||--|{ LINE_ITEM : contains
PRODUCT ||--o{ LINE_ITEM : "ordered in"
USER {
string id PK
string email
string name
}
ORDER {
string id PK
string user_id FK
datetime created_at
float total_amount
}
```
6. Gantt Charts (gantt)
```mermaid
gantt
title Project Delivery Schedule
dateFormat YYYY-MM-DD
section Phase 1 - Architecture
System Design :done, des1, 2026-09-01, 2026-09-07
Security Audit :active, sec1, 2026-09-08, 5d
section Phase 2 - Implementation
Core API Engine : dev1, after sec1, 14d
Frontend Webview : dev2, after sec1, 10d
```
7. Git Graphs (gitGraph)
```mermaid
gitGraph
commit id: "Initial Release"
branch feature/math-engine
checkout feature/math-engine
commit id: "Add KaTeX parser"
commit id: "Fix DOM placeholders"
checkout main
merge feature/math-engine id: "Merge PR [#42](https://github.com/Dragonwinner/markdown-pdf-exporter/issues/42)"
commit id: "Bump v1.0.1" tag: "v1.0.1"
```
8. Mindmaps (mindmap)
```mermaid
mindmap
root((Software Architecture))
Backend
Microservices
Event Sourcing
Caching
Frontend
VS Code Webview
TypeScript
Tailored CSS
Infrastructure
Docker
CI/CD
```
9. Pie Charts (pie)
```mermaid
pie title Task Allocation
"Core Exporter Engine" : 45
"Mermaid & Math Subsystem" : 30
"UI / UX Design" : 15
"Documentation" : 10
```
10. Quadrant Charts (quadrantChart)
```mermaid
quadrantChart
title Feature Impact vs Effort
x-axis Low Effort --> High Effort
y-axis Low Impact --> High Impact
quadrant-1 Strategic Bets
quadrant-2 Quick Wins
quadrant-3 Deprioritized
quadrant-4 Maintenance
"High-DPI Mermaid": [0.3, 0.85]
"KaTeX Math": [0.35, 0.9]
"Headless Puppeteer": [0.85, 0.3]
```
11. Requirement Diagrams (requirementDiagram)
```mermaid
requirementDiagram
requirement test_req {
id: 1
text: System must export PDF locally.
risk: high
verifymethod: test
}
element test_module {
type: module
}
test_module - satisfies -> test_req
```
12. C4 Architecture Diagrams (C4Context)
```mermaid
C4Context
title System Context for Internet Banking
Person(customer, "Banking Customer", "Customer of the bank.")
System(banking_system, "Internet Banking System", "Allows customers to view accounts and make transactions.")
System_Ext(mail_system, "E-mail System", "Internal exchange system.")
Rel(customer, banking_system, "Uses")
Rel(banking_system, mail_system, "Sends e-mails using")
```
📐 KaTeX LaTeX Mathematical Typesetting
The extension integrates KaTeX v0.18.4 for high-fidelity, publication-quality mathematical notation.
Inline Equations
Enclose standard TeX syntax in single dollar signs ($...$):
- Kinetic Energy:
$E_k = \frac{1}{2}mv^2$
- Standard Deviation:
$\sigma = \sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - \mu)^2}$
- Euler's Formula:
$e^{i\theta} = \cos\theta + i\sin\theta$
Display (Block) Equations
Enclose complex multiline formulas, integrals, and matrices in double dollar signs ($$...$$):
$$f(x \mid \mu, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left( -\frac{(x - \mu)^2}{2\sigma^2} \right)$$
$$\begin{bmatrix}
\cos\theta & -\sin\theta \
\sin\theta & \cos\theta
\end{bmatrix}
\begin{bmatrix}
x \
y
\end{bmatrix}
\begin{bmatrix}
x\cos\theta - y\sin\theta \
x\sin\theta + y\cos\theta
\end{bmatrix}$$
$$\oint_C \mathbf{B} \cdot d\mathbf{l} = \mu_0 \left( I_{\text{enc}} + \varepsilon_0 \frac{d\Phi_E}{dt} \right)$$
Safe Code Protection
Equations and dollar signs inside inline code (e.g. `$variable`) or code fences (e.g. ```bash) are preserved without unwanted KaTeX parsing.
🖼️ Smart Local & Relative Image Inlining
Never worry about broken images or missing file references when sharing exported PDFs:
- Supported Image Formats: PNG (
.png), JPEG (.jpg, .jpeg), GIF (.gif), WebP (.webp), SVG (.svg), and BMP (.bmp).
- Relative Path Resolution: Automatically resolves paths relative to the active Markdown file (e.g.
 or ).
- Embedded Base64: Images are converted to in-memory Base64 data URIs before PDF generation, ensuring 100% self-contained documents.
- External Image Support: Secure HTTPS images (e.g.
https://example.com/image.png) are safely rendered when network connectivity is available.
Unlike standard browser "Print to PDF" which frequently cuts lines of text or leaves lone headers at page bottoms, this extension includes an intelligent layout engine:
- Anti-Orphan & Anti-Widow Rules: Headings (
h1–h6) are never left stranded at the bottom of a page without at least their subsequent child content.
- Container Preservation: Tables, code blocks, math formulas, and Mermaid diagrams are measured before rendering to avoid mid-element splits whenever possible.
- High-DPI Raster Scaling: Mermaid diagrams and rich vector content are rendered at 2x or 3x scale factor to preserve crispness when printed on high-resolution physical printers.
- Custom Page Sizes: Native support for standard paper sizes (A4, US Letter, US Legal) in both Portrait and Landscape orientations.
🖱️ Ways to Export
| Action |
How to Trigger |
| Editor Navigation Bar |
Click the Export as PDF $(file-pdf) icon at the top right of any .md editor. |
| Editor Context Menu |
Right-click anywhere in the Markdown editor window and select Export Markdown as PDF. |
| File Explorer Context Menu |
Right-click any .md or .markdown file in the VS Code Explorer and select Export Markdown as PDF. |
| Command Palette |
Press Ctrl+Shift+P (or Cmd+Shift+P), type Export Markdown as PDF, and press Enter. |
⚙️ Configuration & Settings
Fine-tune your export preferences via VS Code Settings (Ctrl+, or Cmd+, → search Markdown PDF):
| Setting |
Default |
Options |
Description |
markdownPdf.previewTheme |
"default" |
default, neutral, dark, forest, base |
Mermaid diagram theme used during export. |
markdownPdf.pageSize |
"a4" |
a4, letter, legal |
Paper format size for the generated PDF document. |
markdownPdf.orientation |
"portrait" |
portrait, landscape |
Page orientation for document compilation. |
markdownPdf.margin |
32 |
10 – 80 |
Document margin size in points (pt). Default is 32pt. |
markdownPdf.highDpi |
2 |
1, 2, 3 |
Rasterization scale factor for Mermaid diagrams (2 = 2x Retina quality). |
Example settings.json
{
"markdownPdf.previewTheme": "neutral",
"markdownPdf.pageSize": "a4",
"markdownPdf.orientation": "portrait",
"markdownPdf.margin": 36,
"markdownPdf.highDpi": 2
}
🆚 Comparison Matrix
| Feature |
Markdown to PDF (with Mermaid & Math) |
Traditional Puppeteer Exporters |
Pandoc / LaTeX Toolchains |
| Installation Size |
< 3 MB |
> 300 MB (Chromium download) |
> 1 GB (TeX Live / Pandoc) |
| Zero External Binaries |
✅ Yes (100% Bundled) |
❌ Requires Chrome/Puppeteer |
❌ Requires CLI toolchain |
| Mermaid Diagram Support |
✅ Flawless (12+ Types) |
⚠️ Limited / Often Broken |
⚠️ Requires external filters |
| KaTeX LaTeX Math |
✅ Native Inline & Display |
⚠️ Hit-or-Miss |
✅ Native |
| Local Image Base64 Inlining |
✅ Automatic |
⚠️ Requires local file server |
⚠️ Path configuration required |
| Anti-Orphan Pagination |
✅ Automatic Heading Retention |
❌ Cuts headings mid-page |
⚠️ Manual LaTeX tweaking |
| Offline & Privacy First |
✅ 100% Offline / Zero Cloud |
⚠️ Often connects to CDNs |
✅ Offline |
| Setup Complexity |
Zero Setup (Plug & Play) |
High (Binary path configuration) |
Very High (LaTeX package errors) |
🔒 Privacy & Security Architecture
- 100% Local Processing: Every parsing, diagram rasterization, math rendering, and PDF assembly step runs entirely inside your local VS Code instance.
- Zero Telemetry: No user data, file contents, filenames, or metrics are ever collected or sent to any remote server.
- Strict Content Security Policy (CSP): The embedded export webview operates under an isolated CSP sandbox (
default-src 'none'; img-src data:; style-src 'nonce-...' 'unsafe-inline'; script-src 'nonce-...';) preventing script injection or unauthorized network activity.
- Safe HTML Sanitization: All parsed markdown content is sanitized through DOMPurify before rendering to safeguard against malicious markdown injections.
❓ Troubleshooting & FAQ
Q: Why didn't my Mermaid diagram render?
A: Ensure your diagram is placed inside a valid fenced code block labeled ```mermaid:
```mermaid
graph TD
A --> B
```
If there is a syntax error in your diagram code, the exporter will render the diagram text alongside a helpful red warning message identifying the syntax error without failing the rest of your document export.
Q: Why are my equations not rendering?
A: Make sure single dollar signs ($...$) for inline math and double dollar signs ($$...$$) for display math are properly paired. Ensure there are no escaped backslashes interfering with the delimiters. Dollar signs inside code blocks (`code`) are intentionally ignored.
Q: Can I export in Landscape mode for wide tables or Gantt charts?
A: Yes! Open your VS Code Settings (Ctrl+,), search for markdownPdf.orientation, and set it to landscape.
Q: Does this work in restricted offline enterprise environments?
A: Yes. The extension has zero runtime downloads and does not require internet access or headless browser binaries.
🛠️ Development & Building
To clone, build, and test the extension locally:
# 1. Clone the GitHub repository
git clone https://github.com/Dragonwinner/markdown-pdf-exporter.git
cd markdown-pdf-exporter
# 2. Install dependencies
npm install
# 3. Type check & build production bundles
npm run compile
# 4. Package VSIX extension locally
npm run package
🤝 Contributing Guide
Contributions from the developer and open-source community are warmly welcome! Whether you are reporting a bug, proposing a new diagram type, or improving documentation, your support is appreciated.
How to Contribute
- Fork the Repository on GitHub: https://github.com/Dragonwinner/markdown-pdf-exporter
- Clone your fork locally:
git clone https://github.com/Dragonwinner/markdown-pdf-exporter.git
cd markdown-pdf-exporter
- Create a descriptive feature branch:
git checkout -b feature/your-feature-name
# or
git checkout -b fix/issue-description
- Make your changes and verify the build:
npm run check # Verifies TypeScript types
npm run compile # Bundles extension and webview runtimes
- Commit your changes following the Conventional Commits format:
git commit -m "feat(mermaid): add quadrant chart high-dpi scaling support"
- Push to your fork and submit a Pull Request targeting the
main branch.
For detailed guidelines, code style, and security rules, please refer to our full CONTRIBUTING.md.
📄 License & Author
Distributed under the MIT License. See LICENSE for full license text.
Crafted with ❤️ by codewithgod
Empowering developers, students, and researchers with beautiful, local-first documentation tooling.
⭐ Star on GitHub • 📦 View Releases