OfficeCLI Mermaid Diagram Conversion to Native Shapes: A Complete Technical Guide
OfficeCLI converts Mermaid text diagrams into fully editable native Office shapes without requiring external image generation, producing documents where users can modify rectangles, diamonds, and connectors directly in Word or PowerPoint.
OfficeCLI, developed by iOfficeAI/OfficeCLI, provides a zero-dependency pipeline that transforms Mermaid DSL descriptions into native Office Open XML drawing elements. This OfficeCLI Mermaid diagram conversion to native shapes eliminates the need for bitmap renders while maintaining full editability in the final document.
How Native Shape Conversion Works
The conversion pipeline operates through four distinct internal stages, requiring no external binaries unless the user explicitly requests image rendering.
Step 1: Mermaid Text Acquisition
The process begins when the CLI reads the diagram definition from the add --type diagram command. The handler accepts the Mermaid source through multiple property keys: mermaid, text, dsl, or src.
In PowerPointHandler.Add.Diagram.cs (lines 29-46), the system retrieves either an inline string or reads a .mmd file from disk. This raw text then feeds directly into the parsing engine without intermediate transformations.
Step 2: Parsing the DSL with MermaidParser
The MermaidParser.Parse method, located in src/officecli/Core/Diagram/MermaidParser.cs (lines 10-62), transforms the raw Mermaid DSL into a language-agnostic DiagramGraph intermediate representation.
This parser handles:
- Flowchart syntax and node-shape wrappers
- Edge operators and directional indicators
- Group expansion for complex diagrams
- Unsupported directive filtering
The resulting DiagramGraph contains nodes, edges, and metadata that remain independent of any specific output format.
Step 3: Layout and Compilation
DiagramCompiler.Compile, found in src/officecli/Core/Diagram/DiagramCompiler.cs (lines 18-34), selects the appropriate layout engine based on the first meaningful line of the Mermaid source.
Currently supported layout engines include:
- FlowchartLayout – Processes standard flowchart TD (top-down) and LR (left-right) syntax
- SequenceLayout – Handles sequence diagram interactions
Each layout engine produces a LaidOutGraph containing geometric coordinates, connection points, and shape specifications that map directly to Office drawing primitives.
Step 4: Native Shape Synthesis
The AddDiagramNative method walks the LaidOutGraph and generates Office Open XML drawing elements (<w:drawing> for Word, <p:spTree> for PowerPoint). This process, detailed in PowerPointHandler.Add.Diagram.cs (lines 64-70), creates native shapes including rectangles, diamonds, circles, and connectors.
Users receive fully editable graphics they can modify, resize, or recolor using standard Office tools, unlike embedded images that require external editing.
Fallback Image Rendering Pipeline
When the user specifies render=image or when the native backend encounters unsupported diagram types, the system falls back to MermaidImageRenderer. This component attempts rendering in the following order:
mmdc– The official Mermaid CLI binary, if installed locally- Headless Browser – Chrome, Chromium, or Edge via
HtmlScreenshotfor high-fidelity rendering
The renderer caches the minified mermaid.min.js library under ~/.officecli/cache, refreshing it daily via UpdateChecker. When rendering completes, the PNG embeds with the original source preserved in the alt attribute using the mermaid: prefix, enabling round-trip editing later.
Practical Code Examples
1. Creating Native Shapes (Default Behavior)
officecli add --type diagram --doc my.pptx \
--properties "mermaid=flowchart TD; A-->B; B-->C"
The handler parses the flowchart syntax, invokes FlowchartLayout, and inserts editable PowerPoint shapes.
2. Forcing PNG Rendering for Unsupported Types
officecli add --type diagram --doc my.docx \
--properties "mermaid=pie; A:30; B:70; render=image"
MermaidImageRenderer.RenderToPngFile executes, attempting mmdc first, then falling back to headless browser rendering.
3. Retrieving Source from Existing Images
// Extract original Mermaid source from a rendered image
var alt = pictureElement.GetAttribute("alt");
// Returns: "mermaid:flowchart TD; A-->B"
if (alt.StartsWith(MermaidImageRenderer.SourceTag))
{
var mermaidSource = alt.Substring(MermaidImageRenderer.SourceTag.Length);
// Process or re-render the original DSL
}
Key Source Files and Architecture
The implementation spans several critical files:
src/officecli/Core/Diagram/DiagramCompiler.cs– Dispatches Mermaid sources to layout engines based on diagram type detectionsrc/officecli/Core/Diagram/MermaidParser.cs– Tokenizes and parses Mermaid DSL into intermediate graph structuressrc/officecli/Core/Diagram/MermaidImageRenderer.cs– Manages PNG rendering, binary detection, and mermaid.js cachingsrc/officecli/Handlers/Pptx/PowerPointHandler.Add.Diagram.cs– PowerPoint-specific command implementation and shape synthesissrc/officecli/Handlers/Word/WordHandler.Add.Diagram.cs– Word document handler for native diagram insertionsrc/officecli/Core/HtmlScreenshot.cs– Browser automation for headless renderingsrc/officecli/Core/UpdateChecker.cs– Daily cache maintenance for the mermaid.js library
Summary
- OfficeCLI Mermaid diagram conversion to native shapes operates entirely within the CLI without external dependencies, producing editable Office graphics
- The four-stage pipeline (acquisition → parsing → layout → synthesis) converts Mermaid DSL into Office Open XML drawing elements
MermaidParserandDiagramCompilerhandle flowcharts and sequence diagrams, with extensibility for additional layout engines- Image fallback via
MermaidImageRenderersupportsmmdcor headless browsers when native rendering is unavailable - Original Mermaid source persists in image
altattributes, enabling round-trip conversion and editing workflows
Frequently Asked Questions
How does OfficeCLI handle Mermaid syntax errors during native conversion?
The MermaidParser validates syntax during the parsing stage and throws MermaidSyntaxException for genuine errors rather than silently failing or producing broken shapes. This provides clear feedback to the caller about which line or token caused the failure, allowing users to correct the DSL before retrying the conversion.
Can I convert complex Mermaid diagrams with subgraphs to native PowerPoint shapes?
Yes, the FlowchartLayout engine supports group expansion and subgraph processing as implemented in the layout compilation stage. The LaidOutGraph structure preserves hierarchical relationships, and AddDiagramNative synthesizes grouped shapes that maintain their containment relationships as PowerPoint groups, allowing users to collapse, expand, or edit subgraphs individually.
What happens if neither mmdc nor a headless browser is available for image rendering?
If both mmdc and browser automation fail, MermaidImageRenderer returns a specific error indicating the rendering backend is unavailable. The system does not fall back to the native synthesizer automatically when render=image is explicitly requested, preserving the user's intent to receive a bitmap. However, removing the render=image property triggers the native path, which has zero external dependencies and always succeeds for supported diagram types.
Where does OfficeCLI store the cached mermaid.js library for image rendering?
The library caches at ~/.officecli/cache under the user's home directory. UpdateChecker manages this cache, checking for updates daily and refreshing the minified mermaid.min.js file when newer versions become available. This prevents repeated network fetches during batch operations while ensuring the CLI uses current Mermaid syntax support.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →