OfficeCLI Diagram and Mermaid Integration for Office Shapes: A Developer Guide

OfficeCLI embeds Mermaid diagrams into Word, Excel, and PowerPoint as native editable shapes or high-fidelity PNGs through a three-stage parsing, compilation, and rendering pipeline.

OfficeCLI is an open-source .NET command-line tool for generating Office documents programmatically. Its OfficeCLI diagram and Mermaid integration for Office shapes stands out as one of the most sophisticated features—converting text-based Mermaid diagrams into either native DrawingML shapes or pixel-perfect PNG renders without manual drawing tools.

Architecture Overview

The diagram subsystem follows a strict separation of concerns across three layers, as implemented in the iOfficeAI/OfficeCLI repository:

Layer Responsibility Entry Point
Parsing Tokenize Mermaid syntax into intermediate representation MermaidParser.Parse()
Compilation Detect diagram type and compute layout DiagramCompiler.Compile()
Rendering Output native Office shapes or PNG images DiagramCompiler (native) / MermaidImageRenderer (PNG)

Parsing Layer: MermaidParser.cs

The parsing layer in src/officecli/Core/Diagram/MermaidParser.cs converts raw Mermaid text into a DiagramGraph object.

Unicode-Aware Node Identifiers

Node IDs accept any Unicode letter or digit via the pattern \p{L}\p{N}, enabling CJK characters, accented letters, and international labels without escaping.

Shape Recognition via Regex Patterns

The ShapePats collection recognizes Mermaid node syntax and maps supported shapes:

  • [] — rectangle
  • {} — diamond (decision)
  • ([)]) — stadium (pill shape)
  • [()], [(database)] — cylinder/database

Edge and Group Handling

The Link regex parses arrow operators including --, ->, -.-, and ==>, with optional mid-edge labels. The Group and SplitTop methods expand ampersand-separated tokens like A & B[Label] while respecting bracket depth for nested constructs.

Error resilience: The parser never throws exceptions—unknown tokens are silently skipped, ensuring pipeline stability.

Compilation Layer: DiagramCompiler.cs

src/officecli/Core/Diagram/DiagramCompiler.cs transforms the parsed graph into a layout-complete model.

Diagram Type Detection

The compiler reads the first meaningful non-comment line to identify:

  • flowchart or graphFlowchartLayout.Layout()
  • sequenceDiagramSequenceLayout.Layout()

Unsupported diagram types (gantt, class, state, etc.) raise ArgumentException with descriptive messaging.

Layout Engines

  • FlowchartLayout.cs: Grid-based positioning with edge routing
  • SequenceLayout.cs: Actor lifelines and message placement

Both return a LaidOutGraph containing absolute coordinates, shape geometries, and connector paths—ready for either rendering path.

Rendering Paths: Native vs. PNG

OfficeCLI provides two mutually exclusive rendering strategies, selectable via --render native (default) or --render png.

Native Synthesizer (Dependency-Free)

The native path walks the LaidOutGraph and synthesizes Office DrawingML shapes using:

  • DrawingColorBuilder — theme and RGB color mapping
  • DrawingEffectsHelper — shadows, reflections, bevels

This produces fully editable shapes in Word, Excel, or PowerPoint with no external tooling required.

High-Fidelity PNG Renderer

src/officecli/Core/Diagram/MermaidImageRenderer.cs implements a three-tier fallback cascade:

  1. mmdc — Official Mermaid CLI (@mermaid-js/mermaid-cli)
  2. Headless Chrome — Chromium/Edge browser with mermaid.min.js
  3. Native synthesizer — Automatic fallback if both fail

Caching and Performance

Mermaid scripts are cached to ~/.officecli/cache/mermaid-<version>.min.js. The RefreshCacheIfPresent() method checks daily for updates, eliminating redundant downloads.

Style Injection with YAML Front-Matter

Advanced styling via ESM Mermaid is supported through ComposeSource():

---
config:
  theme: dark
  layout: elk
---

The renderer detects this block via SourceNeedsEsm() and routes to BuildHtmlEsm() instead of the UMD path.

Error Handling Consistency

Syntax errors surface as MermaidSyntaxException with original line numbers. The Chrome path extracts errors from a hidden <pre id="mmderr"> DOM element, ensuring identical CLI feedback regardless of backend.

PNG Capture Mechanism

Backend Implementation
mmdc Temporary .mmd file → mmdc -o output.png
Chrome BuildHtml()/BuildHtmlEsm()HtmlScreenshot.CaptureChromeSized() → SVG viewBox extraction → cropped PNG

The Src/officecli/Core/HtmlScreenshot.cs utility drives headless browser automation, DOM dumping, and screenshot capture.

CLI Usage

Add diagrams to Office documents from the command line:


# Native Office shapes (default)

officecli add --type diagram \
  --source "flowchart TD; A[Start] --> B{Decision}; B -->|Yes| C[Result]" \
  --output document.docx

# High-fidelity PNG render

officecli add --type diagram \
  --source @workflow.mmd \
  --render png \
  --output presentation.pptx

# Inline heredoc

officecli add --type diagram --source - --render native <<'EOF'
sequenceDiagram
    Alice->>Bob: Hello
    Bob->>Alice: Hi there
EOF

File paths use @ prefix; omitting --render defaults to native shape synthesis.

Programmatic API (C#)

Integrate diagram generation directly in .NET applications:

using OfficeCli.Core.Diagram;

// Parse and compile
string mermaid = @"
flowchart LR
    A[Start] --> B{Decision}
    B -->|Yes| C[Result]
    B -->|No| D[Abort]
";

LaidOutGraph layout = DiagramCompiler.Compile(mermaid);

// Option 1: Native Office shapes
var document = new OfficeWordDocument();
document.AddNativeDiagram(layout);  // Editable DrawingML

// Option 2: High-fidelity PNG
if (MermaidImageRenderer.IsAvailable())
{
    using var pngStream = MermaidImageRenderer.RenderToStream(mermaid);
    document.InsertImage(pngStream);
}

Supported Mermaid Features

Feature Native Shapes PNG Render
Flowcharts (TD, LR, BT, RL) ✅ Full ✅ Full
Sequence diagrams ✅ Full ✅ Full
Node shapes (rect, diamond, stadium, database) ✅ Subset ✅ All
Edge labels
Subgraphs/groups
Gantt, class, state, ER diagrams
Custom themes (dark, forest, etc.) ❌ (uses Office theme)
ELK/layout engines

Key Source Files

Summary

  • OfficeCLI diagram and Mermaid integration for Office shapes operates through parsing → compilation → rendering stages with clean interfaces between each
  • The native path (DiagramCompiler) yields editable Office DrawingML shapes without external dependencies
  • The PNG path (MermaidImageRenderer) provides pixel-perfect renders via mmdc or headless Chrome with graceful degradation
  • Unicode identifiers, YAML front-matter styling, and consistent error handling make the system production-ready for international and enterprise use
  • Both CLI (add --type diagram) and C# API (DiagramCompiler.Compile()) expose identical functionality

Frequently Asked Questions

What Mermaid diagram types does OfficeCLI support natively?

OfficeCLI natively supports flowcharts (all directions: TD, LR, BT, RL) and sequence diagrams through the native shape synthesizer. Other diagram types—including Gantt, class, state, ER, and pie charts—are unsupported for native rendering but work via the PNG path using mmdc or Chrome.

How does OfficeCLI handle Mermaid syntax errors?

Syntax errors propagate as MermaidSyntaxException with original line numbers preserved. When using the Chrome fallback, errors are extracted from the hidden <pre id="mmderr"> DOM element to maintain consistent error messaging across all backends.

Can I use custom Mermaid themes with OfficeCLI?

Yes, but only via the PNG renderer. Include a YAML front-matter block in your Mermaid source specifying theme: dark, theme: forest, or other values. The MermaidImageRenderer detects this via SourceNeedsEsm() and routes to the ESM build path. Native shape rendering ignores theme directives and uses Office document themes instead.

What happens if mmdc and Chrome are both unavailable?

The PNG renderer cascade attempts mmdc first, then headless Chrome/Chromium/Edge. If both fail, the caller can explicitly request native rendering with --render native or handle the failure programmatically. The native synthesizer has zero external dependencies and works on any system where OfficeCLI runs.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →