Tools

Complete Guide to Exporting Mermaid Diagrams: PNG, SVG, PDF One-Stop Solutions

May 27, 2026
7 min read
mermaid2img

Mermaid's "Diagram as Code" philosophy greatly improves drawing efficiency, but in practice, we often need to export completed diagrams into common image formats for insertion into PowerPoint, Word, PDF, or blog articles. Different use cases demand different export formats, image quality, and ease of operation.

This article systematically reviews the four main export pathways for Mermaid diagrams, helping you choose the most suitable solution for your needs.

Export Format Comparison

Before diving into specific methods, let's understand the characteristics of each export format:

FormatCharacteristicsBest ForNotes
PNGLossless bitmap, wide compatibilityBlogs, documents, presentationsMay pixelate when enlarged; export at 2x resolution recommended
JPGLossy compression, smaller file sizePhoto-like content, web displayNot ideal for text-heavy diagrams with fine lines
SVGVector format, infinite scalabilityTechnical docs, print, webSmallest file size; supports interactivity and animation
PDFMixed vector/raster, precise layoutAcademic papers, formal reportsHighest fidelity; ideal for printing

For technical diagrams, SVG is the top choice because it stays crisp at any scale; PNG is the most universal format supported by virtually every platform; PDF is best for print or formal publication scenarios.

For users who rarely use the command line, online tools are the simplest and most direct option.

Mermaid2Img

Mermaid2Img is a free Mermaid live editor with image export specifically designed for Mermaid diagram export. It runs entirely in the browser with no registration required.

Core Features:

  • Real-time preview: Instantly render diagrams as you type Mermaid code
  • Multi-format export: Supports PNG, JPG, SVG, and PDF
  • High-definition output: PNG supports 2x resolution for Retina displays
  • Privacy protection: All processing happens locally in the browser; code is never uploaded to a server
  • Error highlighting: Syntax errors are flagged in real time for quick fixes

Usage Steps:

  1. Open the Mermaid online editor
  2. Paste your Mermaid code into the left editor
  3. The right panel automatically renders a preview
  4. Select your target format and click the download button
graph TD
    A[Open Mermaid2Img] --> B[Paste Mermaid Code]
    B --> C[Preview in Real Time]
    C --> D[Select Export Format]
    D --> E[Download HD Image]

Mermaid Live Editor

The official Mermaid online editor (mermaid.live) also supports export, but it's more basic—only PNG and SVG formats are available, and resolution cannot be adjusted.

If your search intent is "Mermaid live editor export PNG/SVG/PDF", use Mermaid2Img's Mermaid live editor instead. It keeps the fast live preview workflow while adding PNG, JPG, SVG, and PDF export from the same browser workspace.

Method 2: Mermaid CLI Command-Line Tool

For developers and technical teams, the Mermaid CLI offers automation and batch processing capabilities, especially suited for integration into CI/CD pipelines.

Installation

# Global install
npm install -g @mermaid-js/mermaid-cli

# Or run without installation via npx
npx -p @mermaid-js/mermaid-cli mmdc -h

Basic Export Commands

# Export as SVG (default format)
mmdc -i diagram.mmd -o output.svg

# Export as PNG
mmdc -i diagram.mmd -o output.png

# Export as PDF
mmdc -i diagram.mmd -o output.pdf

Advanced Options

# Specify theme (default / dark / forest / neutral)
mmdc -i input.mmd -o output.svg -t dark

# Set background color (supports color names or hex)
mmdc -i input.mmd -o output.png -t dark -b transparent

# Set output dimensions
mmdc -i input.mmd -o output.png -w 1920 -H 1080

# Use a custom CSS file
mmdc -i input.mmd -o output.svg --cssFile custom.css

Batch Processing

Combine with shell scripts for batch conversion:

# Convert all .mmd files in a directory to PNG
for file in diagrams/*.mmd; do
    mmdc -i "$file" -o "exports/$(basename "$file" .mmd).png"
done

Integration into package.json

{
  "scripts": {
    "build:diagrams": "mmdc -i diagrams/ -o assets/ -t dark"
  }
}

Method 3: Programmatic API Export

If you need to generate diagrams dynamically within an application, you can use Mermaid's programmatic API.

Node.js Environment

import { run } from '@mermaid-js/mermaid-cli'

await run(
  'input.mmd',
  'output.svg',
  { theme: 'dark', backgroundColor: '#1e1e1e' }
)

Browser Environment

In the browser, use Mermaid's render method to generate an SVG string, then convert it to an image for download:

import mermaid from 'mermaid'

async function exportDiagram(code, format = 'svg') {
  const { svg } = await mermaid.render('diagram-id', code)
  
  if (format === 'svg') {
    const blob = new Blob([svg], { type: 'image/svg+xml' })
    downloadBlob(blob, 'diagram.svg')
  } else {
    // Convert SVG to Canvas then export PNG
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.width * 2  // 2x resolution
      canvas.height = img.height * 2
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
      canvas.toBlob(blob => downloadBlob(blob, 'diagram.png'))
    }
    img.src = 'data:image/svg+xml;base64,' + btoa(svg)
  }
}

Method 4: Native Platform Support

Some platforms natively support Mermaid rendering without manual export:

PlatformSupport MethodExport Approach
GitHub / GitLabAuto-render in Markdown blocksScreenshot or browser extension
NotionCode block with Mermaid languageDirect screenshot
ObsidianInstall Mermaid pluginPlugin provides export feature
TyporaNative Mermaid supportAuto-convert on Markdown export
MkDocsmermaid2 pluginAuto-generates SVG during build

For these platforms, if built-in export doesn't meet your needs, you can still use tools like Mermaid2Img for higher-quality output.

Export Quality Optimization Tips

1. Choose the Right Resolution

  • Web display: 1x resolution is sufficient
  • Retina / HiDPI screens: Export at 2x resolution
  • Print: 300 DPI; export SVG or high-resolution PNG recommended

2. Handle Transparent Backgrounds

# CLI transparent background
mmdc -i input.mmd -o output.png -b transparent

Online tools like Mermaid2Img usually support transparent backgrounds too—just check the option when exporting PNG.

3. Custom Themes and Colors

Default themes may not suit all scenarios. Customize via a config file:

{
  "theme": "base",
  "themeVariables": {
    "primaryColor": "#e1f5fe",
    "primaryTextColor": "#01579b",
    "primaryBorderColor": "#0288d1",
    "lineColor": "#616161",
    "secondaryColor": "#fff3e0",
    "tertiaryColor": "#e8f5e9"
  }
}

Use the config file:

mmdc -i input.mmd -o output.svg --configFile theme.json

4. Font Embedding Issues

When exporting SVG, special fonts may render inconsistently on other devices. Solutions:

  • Prefer system default fonts (e.g., sans-serif)
  • Convert text to paths (CLI doesn't support this; use Inkscape or similar for post-processing)
  • Export PNG to avoid font compatibility issues

Solution Comparison Summary

SolutionEase of UseAutomationFormat SupportPrivacyBest For
Mermaid2Img⭐ EasyManualPNG/JPG/SVG/PDF⭐⭐⭐ ExcellentAll users
Mermaid CLI⭐⭐ MediumScript automationPNG/SVG/PDF⭐⭐⭐ ExcellentDevelopers
Programmatic API⭐⭐⭐ ComplexFull automationDepends on implementation⭐⭐⭐ ExcellentEngineers
Native Platform⭐ EasyAuto-renderUsually display only⭐⭐ ModeratePlatform users

Recommendations

  • Occasional use,追求便捷: Choose online tools like Mermaid2Img—open and use instantly, zero config
  • Team collaboration, doc automation: Use Mermaid CLI integrated into your build pipeline to keep docs and code in sync
  • Product feature integration: Call the programmatic API to provide diagram generation and export within your app
  • Quick sharing: Leverage native support on GitHub, Notion, and other platforms by embedding code blocks directly

No matter which export method you choose, the core goal is to let your Mermaid diagrams convey information clearly and accurately across all scenarios. Mermaid2Img, as a tool specifically optimized for export use cases, strikes the best balance between convenience, format support, and output quality—making it our recommended daily-use solution.