vt-c-mermaid-to-images¶
Converts Mermaid diagram files (.mmd) to PNG images using mmdc CLI with robust 5-method fallback strategy for error recovery. Validates image dimensions, quality, and file integrity. Handles batch processing and provides detailed logging. Use when you have .mmd files that need to be rendered as PNG images for documentation or presentations.
Plugin: core-standards
Category: Documentation Pipeline
Command: /vt-c-mermaid-to-images
Mermaid to Images Converter¶
Overview¶
This skill converts Mermaid diagram files (.mmd) to high-quality PNG images using the Mermaid CLI (mmdc). It implements a robust 5-method fallback strategy to handle various edge cases and ensures reliable image generation even with complex or problematic diagrams.
Intent Constraints¶
This skill MUST NOT: - Silently skip a diagram that fails all 5 conversion methods - Overwrite an existing PNG without verifying the new output is valid (non-empty, correct dimensions) - Continue batch processing after a critical failure without reporting the failed file
This skill MUST STOP and surface to the user when: - mmdc is not installed or returns a version incompatibility error - A generated PNG has zero-byte size or corrupt image headers - More than 30% of diagrams in a batch fail conversion
Prerequisites¶
Required Software¶
# Check if mmdc is installed
mmdc --version # Should be >= 10.2.4
# Install if needed
npm install -g @mermaid-js/mermaid-cli
Recommended Versions¶
- Mermaid CLI: 10.2.4 or higher
- Node.js: 16+ or higher
- Puppeteer: Automatically installed with mermaid-cli
Quick Start¶
Convert Single File¶
Batch Convert Directory¶
python scripts/batch_generate.py \
--input-dir docs/markdown_mermaid/mermaid/ \
--output-dir docs/markdown_mermaid/images/
With Custom Dimensions¶
python scripts/generate_image.py \
--input diagram.mmd \
--output diagram.png \
--width 1200 \
--height 800
5-Method Fallback Strategy¶
The skill uses a progressive fallback approach to handle difficult diagrams:
Method 1: Standard Generation (Default)¶
When it works: 90%+ of diagrams When it fails: Complex layouts, special characters
Method 2: Config File Method¶
Uses custom Puppeteer configuration with increased timeouts and memory.
When it works: Diagrams that timeout with Method 1 When it fails: Diagrams with syntax errors
Method 3: BR Tag Fix¶
# Pre-process diagram to replace <br> with <br/>
python scripts/fix_br_tags.py input.mmd > fixed.mmd
mmdc -i fixed.mmd -o output.png
When it works: Diagrams with HTML line breaks When it fails: Other syntax issues
Method 4: Graph Conversion¶
# Convert flowchart TD to graph TD
python scripts/convert_to_graph.py input.mmd > converted.mmd
mmdc -i converted.mmd -o output.png
When it works: Flowcharts with compatibility issues When it fails: Non-flowchart diagrams
Method 5: Simplify Diagram¶
# Simplify complex diagram structure
python scripts/simplify_diagram.py input.mmd > simple.mmd
mmdc -i simple.mmd -o output.png
When it works: Overly complex diagrams Last resort: Manual intervention needed
Image Validation¶
Automatic Validation Checks¶
After generation, images are validated for:
# Validation criteria
validation = {
'file_exists': True,
'file_size_bytes': > 0,
'file_size_threshold': > 1024, # At least 1KB
'dimensions_valid': width > 0 and height > 0,
'aspect_ratio_reasonable': 0.2 < (width/height) < 5.0,
'format_valid': 'PNG'
}
Validation Script¶
python scripts/validate_images.py \
--input-dir docs/markdown_mermaid/images/ \
--min-size 1024 \
--max-width 2400 \
--max-height 1800
Output:
{
"total_images": 35,
"valid": 34,
"invalid": 1,
"issues": [
{
"file": "diagram_12.png",
"issue": "file_size_too_small",
"size": 512,
"threshold": 1024
}
]
}
Dimension Management¶
Smart Dimension Detection¶
The skill can automatically determine optimal dimensions:
# Analyze .mmd file content
optimal_dims = analyze_diagram_complexity(mermaid_file)
# Returns recommendation
{
'width': 800, # For simple diagrams
'height': 600,
'reason': 'Low complexity, standard dimensions'
}
# Or for complex diagrams
{
'width': 1200,
'height': 1600,
'reason': 'High node count, increased dimensions'
}
Dimension Presets¶
# Small (presentations)
--preset small # 640x480
# Medium (documentation, default)
--preset medium # 800x600
# Large (detailed diagrams)
--preset large # 1200x900
# Extra Large (posters, prints)
--preset xlarge # 1600x1200
Logging and Monitoring¶
Comprehensive Logging¶
Every generation creates a detailed log:
Log contents:
2025-10-23 14:50:30 - INFO - ============================================================
2025-10-23 14:50:30 - INFO - IMAGE GENERATION SESSION
2025-10-23 14:50:30 - INFO - ============================================================
2025-10-23 14:50:30 - INFO - Processing diagram 1: architecture_01_flowchart.mmd
2025-10-23 14:50:30 - INFO - Method 1 (Standard): Attempting...
2025-10-23 14:50:32 - INFO - ✓ Generated: architecture_01_flowchart.png (45,234 bytes)
2025-10-23 14:50:32 - INFO - Validation: PASS (dims: 800x1150, size: 45KB)
Progress Tracking¶
For batch operations:
Output:
Processing diagrams: [=====> ] 6/10 (60%)
Current: payment-flow.mmd
Status: Generating with Method 1...
Error Handling¶
Common Errors and Solutions¶
Error 1: mmdc Command Not Found¶
Symptom:
Solution:
Error 2: Puppeteer Launch Failed¶
Symptom:
Solution:
# Install Chromium dependencies (Linux)
sudo apt-get install -y chromium-browser
# Or use Method 2 with custom config
python scripts/generate_image.py --method config
Error 3: Output File Empty (0 bytes)¶
Symptom:
Diagnosis:
# Check diagram syntax
python scripts/validate_syntax.py input.mmd
# Try fallback methods
python scripts/generate_image.py --input input.mmd --fallback
Solution:
- Usually a syntax error in the .mmd file
- Run through Methods 2-5 automatically with --fallback flag
Error 4: Timeout on Large Diagrams¶
Symptom:
Solution:
# Use Method 2 with increased timeout
python scripts/generate_image.py \
--input large-diagram.mmd \
--method config \
--timeout 60000
Error Handling (context: fork)¶
This skill runs with context: fork — it executes as an isolated sub-agent that returns only its output to the parent conversation. Fork sub-agents CANNOT interact with the user.
Critical rules for fork context:
-
NEVER ask interactive questions. No "Would you like...?", no "Should I...?", no AskUserQuestion calls. The question will be swallowed, the sub-agent will die, and the parent conversation receives no output at all.
-
If a file write fails, report it inline and continue. Use this format:
Warning — file not persisted: Could not write
{filename}. The full content is included in the output above. To persist, copy the content manually or re-run with write permissions. -
Always produce the full formatted output as the primary deliverable. The generation manifest and progress summary returned to the parent conversation is the primary output. File persistence is secondary. Complete all image generation and validation BEFORE attempting to write summary files.
-
Always end with a TL;DR summary. After all processing, output a concise summary as the absolute last output. Nothing may follow it. Max 10 lines between delimiters.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TL;DR
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Converted: [N]/[M] diagrams successful
Validation: [N] passed | [N] failed
Fallbacks used: [N] (methods [list])
[If failures]: Failed: [filenames]
Next: [Review failed diagrams / Images ready for use]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Integration with Other Skills¶
Works With¶
- mermaid-diagrams-branded: Receives branded .mmd files
- markdown-diagram-processor: Provides images for markdown embedding
- document-converter-branded: Supplies images for PDF/Word
- docs-pipeline-orchestrator: Part of the full pipeline
Input Format¶
Expects .mmd files with or without theme configuration:
%%{init: {'theme':'base'}}%%
flowchart TD
Start --> End
Or plain Mermaid:
flowchart TD
Start --> End
Output Format¶
Generates PNG files following naming convention:
- Input:
architecture_01_flowchart.mmd - Output:
architecture_01_flowchart.png
Location: docs/markdown_mermaid/images/*.png
Manifest Management¶
Generation Manifest¶
Creates a manifest file tracking all conversions:
{
"session_id": "img_gen_20251023_145030",
"timestamp": "2025-10-23T14:50:30Z",
"total_diagrams": 35,
"successful": 34,
"failed": 1,
"diagrams": [
{
"index": 1,
"mermaid_file": "mermaid/architecture_01_flowchart.mmd",
"image_file": "images/architecture_01_flowchart.png",
"status": "success",
"method_used": "standard",
"dimensions": {"width": 800, "height": 1150},
"file_size": 45234,
"generation_time_ms": 2145,
"command": "mmdc -i ... -o ..."
}
]
}
Performance Optimization¶
Parallel Processing¶
For large batches, use parallel processing:
python scripts/batch_generate.py \
--input-dir docs/markdown_mermaid/mermaid/ \
--output-dir docs/markdown_mermaid/images/ \
--parallel 4 # Process 4 diagrams simultaneously
Performance: - Sequential: ~2-3 seconds per diagram - Parallel (4 workers): ~0.5-1 second per diagram (effective)
Caching¶
Skip regeneration of unchanged diagrams:
python scripts/batch_generate.py \
--input-dir mermaid/ \
--output-dir images/ \
--skip-existing \
--check-modified
Only regenerates if: - Output PNG doesn't exist - Input .mmd is newer than output PNG - Force flag is used
Advanced Features¶
Custom Background Colors¶
python scripts/generate_image.py \
--input diagram.mmd \
--output diagram.png \
--background transparent # or '#F5F5F5', etc.
Scale Factor¶
For high-DPI displays:
python scripts/generate_image.py \
--input diagram.mmd \
--output diagram.png \
--scale 2.0 # 2x resolution for retina displays
Quality Settings¶
python scripts/generate_image.py \
--input diagram.mmd \
--output diagram.png \
--quality high # or 'medium', 'low'
Quality presets: - low: Faster, smaller files (presentations) - medium: Balanced (default, documentation) - high: Best quality (print, posters)
File Structure¶
~/.claude/skills/vt-c-mermaid-to-images/
├── SKILL.md (this file)
├── scripts/
│ ├── generate_image.py # Single image generation
│ ├── batch_generate.py # Batch processing
│ ├── validate_images.py # Image validation
│ ├── validate_syntax.py # Mermaid syntax check
│ ├── fix_br_tags.py # Method 3: BR fix
│ ├── convert_to_graph.py # Method 4: Graph conversion
│ ├── simplify_diagram.py # Method 5: Simplification
│ └── analyze_complexity.py # Dimension recommendation
└── config/
├── puppeteer-config.json # Custom Puppeteer settings
└── dimension-presets.json # Dimension templates
Best Practices¶
✅ Do¶
- Always validate images after generation
- Use appropriate dimensions for output medium
- Enable logging for production workflows
- Use fallback methods for reliability
- Batch process when possible for efficiency
❌ Don't¶
- Generate images larger than needed (waste of resources)
- Skip validation (may miss 0-byte files)
- Use overly complex diagrams (split into multiple)
- Ignore errors (they compound in pipelines)
- Hardcode dimensions (use presets or analysis)
Troubleshooting Guide¶
Diagnostic Workflow¶
# Step 1: Check prerequisites
mmdc --version
node --version
# Step 2: Validate diagram syntax
python scripts/validate_syntax.py diagram.mmd
# Step 3: Try generation with logging
python scripts/generate_image.py \
--input diagram.mmd \
--output diagram.png \
--verbose \
--log generation.log
# Step 4: If failed, check log
cat logs/generation.log
# Step 5: Try fallback methods
python scripts/generate_image.py \
--input diagram.mmd \
--output diagram.png \
--fallback \
--verbose
Version History¶
- v1.0 (2025-10-23): Initial release
- 5-method fallback strategy
- Comprehensive validation
- Batch processing support
- Compatible with mmdc 10.2.4+
References¶
- Mermaid CLI: https://github.com/mermaid-js/mermaid-cli
- Puppeteer: https://pptr.dev/
- Image validation standards: PNG specification