DEV Community

Cover image for πŸ“ Diagram-as-Code: Graphviz HTML Labels to Match Existing Visuals
Benoit COUETIL πŸ’« for Zenika

Posted on

πŸ“ Diagram-as-Code: Graphviz HTML Labels to Match Existing Visuals

Most diagram tools force a choice: convenience or control. Mermaid is quick but inflexible. PlantUML is rich but opinionated about layout. Graphviz's DOT language hides a secret weapon, HTML-like labels, that turns a simple graph engine into a pixel-perfect rendering machine. Here we explore the techniques that make it possible, from nested tables to port-based edges, with a real-world CI pipeline visualization as our showcase.

Initial thoughts

The diagram-as-code movement has given us fantastic tools. Mermaid lets us sketch flowcharts in seconds. PlantUML handles UML with flair. Kroki unifies dozens of engines behind a single API. For most needs, these tools are more than enough.

But then comes that diagram. The one where auto-layout produces spaghetti, where we need icons next to text, where containers must have rounded borders with precise background colors. The one where we open the PlantUML docs, scroll past 47 layout hints, and think: "there has to be a better way."

There is. And it's been hiding inside the tool that PlantUML itself relies on: Graphviz.

PlantUML uses Graphviz's dot engine under the hood for layout. But most developers only know DOT as "the language that draws circles with arrows." What they don't know is that DOT supports a full HTML-like label syntax, <TABLE>, <TR>, <TD>, <IMG>, letting us build complex, styled, pixel-precise components directly inside graph definitions.

In this article, we go from basic DOT to production-ready pipeline diagrams, one technique at a time.

1. Beyond bubbles and arrows

Most encounters with DOT look like this:

digraph {
  rankdir=LR
  node [shape=box style=rounded]
  Lint -> Build -> Test -> Deploy
}
Enter fullscreen mode Exit fullscreen mode

Diagram

Nodes, edges, maybe a few colors. Perfectly fine for dependency graphs and quick sketches. And then we hit a wall: "we need a box with a header and a list of items inside, maybe an icon on each row." At which point most people switch to a different tool entirely.

That's a shame, because DOT already supports all of this. The documentation is just... not great at advertising it. (To be fair, the official Graphviz docs read like they were written during a compiler course in 1998 and preserved in amber ever since.)

The trick lies in a single line from the shapes documentation:

"The record-based shape has largely been superseded and greatly generalized by HTML-like labels."

HTML-like labels are DOT's best-kept secret. Instead of a plain string, we pass a full HTML structure wrapped in angle brackets. Combined with shape=none (which removes the default ellipse), we get absolute control over what a node looks like:

digraph {
  node [shape=none margin=0 fontname="Arial" fontsize=11]

  stage [label=<
    <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#e9ecef" STYLE="rounded">
      <TR><TD ALIGN="LEFT" CELLPADDING="8"><B>Build</B></TD></TR>
      <TR><TD CELLPADDING="5">
        <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="4" BGCOLOR="white" STYLE="rounded">
          <TR><TD ALIGN="LEFT">build-api</TD></TR>
          <TR><TD ALIGN="LEFT">build-web</TD></TR>
          <TR><TD ALIGN="LEFT">build-worker</TD></TR>
        </TABLE>
      </TD></TR>
    </TABLE>>]
}
Enter fullscreen mode Exit fullscreen mode

Diagram

Wait: is that a nested HTML table inside a DOT node? Yes. And it renders exactly as expected: a gray rounded container with a bold header and a white inner card listing items. The Graphviz team essentially embedded a mini layout engine inside the node renderer, and barely told anyone about it. (Classic engineer move.)

2. The pixel-perfect toolkit

Now that we know HTML labels exist, let's explore the full toolkit available.

Container cards with nested tables

The two-level nested table pattern is the foundation of everything. The outer table provides the container styling, the inner table provides the content:

<TABLE BGCOLOR="#e9ecef" STYLE="rounded" ...>
  <TR><TD><B>Header</B></TD></TR>
  <TR><TD>
    <TABLE BGCOLOR="white" STYLE="rounded" ...>
      <!-- content rows -->
    </TABLE>
  </TD></TR>
</TABLE>
Enter fullscreen mode Exit fullscreen mode

Key attributes at our disposal:

  • BGCOLOR: cell or table background color (any hex value)
  • STYLE="rounded": rounded corners on <TABLE> elements
  • BORDER, CELLBORDER, CELLSPACING, CELLPADDING: full spacing control
  • ALIGN, VALIGN: text alignment within cells
  • WIDTH, HEIGHT, FIXEDSIZE="TRUE": explicit dimensions
  • <B>, <I>, <U>, <FONT>: inline text formatting
  • <BR ALIGN="LEFT"/>: line breaks with alignment control
  • <IMG>: embedded images in cells

This is not a toy subset. We can build entire UI-like components with it.

Embedding icons in cells

Need a status icon next to each row? The <IMG> tag fits naturally inside a <TD>:

<TR>
  <TD FIXEDSIZE="TRUE" WIDTH="25" HEIGHT="35">
    <IMG SRC="success.png" SCALE="TRUE"/>
  </TD>
  <TD ALIGN="LEFT" WIDTH="150" HEIGHT="35">
    build-api
  </TD>
</TR>
Enter fullscreen mode Exit fullscreen mode

FIXEDSIZE="TRUE" prevents the cell from expanding beyond its declared dimensions. SCALE="TRUE" on the image makes it fit within those bounds.

Note: Graphviz only supports raster images (PNG, JPG) in <IMG> tags, not SVG. If our icons are SVG, we need to convert them first: a quick sharp or ImageMagick call handles that.

Surgical connections with ports

This is where things get really powerful. Every <TD> can have a PORT attribute, turning it into a named anchor point for edges:

digraph {
  rankdir=LR
  node [shape=none margin=0 fontname="Arial" fontsize=11]
  edge [dir=none color="#bbbbbb" penwidth=1.5]

  build [label=<
    <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#e9ecef" STYLE="rounded">
      <TR><TD PORT="hdr" ALIGN="LEFT" CELLPADDING="8"><B>Build</B></TD></TR>
      <TR><TD CELLPADDING="5">
        <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="4" BGCOLOR="white" STYLE="rounded">
          <TR><TD ALIGN="LEFT" PORT="api">build-api</TD></TR>
          <TR><TD ALIGN="LEFT" PORT="web">build-web</TD></TR>
        </TABLE>
      </TD></TR>
    </TABLE>>]

  test [label=<
    <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#e9ecef" STYLE="rounded">
      <TR><TD PORT="hdr" ALIGN="LEFT" CELLPADDING="8"><B>Test</B></TD></TR>
      <TR><TD CELLPADDING="5">
        <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="4" BGCOLOR="white" STYLE="rounded">
          <TR><TD ALIGN="LEFT" PORT="sonar">sonar-api</TD></TR>
          <TR><TD ALIGN="LEFT" PORT="unit">unit-tests</TD></TR>
        </TABLE>
      </TD></TR>
    </TABLE>>]

  build:hdr:e -> test:hdr:w
  build:api:e -> test:sonar:w [style=dashed]
  build:api:e -> test:unit:w [style=dashed]
}
Enter fullscreen mode Exit fullscreen mode

Diagram

The syntax build:api:e -> test:sonar:w means: "draw an edge from the east side of the api port in the build node to the west side of the sonar port in the test node." The compass suffixes (:e, :w, :n, :s) give us surgical control over where edges attach.

No more arrows flying across the diagram in unexpected directions. Finally, a connection that goes exactly where we point it, unlike most WebSocket implementations.

Dynamic width calculation

When generating DOT programmatically, we can compute cell widths based on content length:

const CHAR_W = 5.3;  // approximate character width (Arial 11pt)
const ICON_W = 25;
const PADDING = 4;
const RIGHT_MARGIN = 12;

const maxNameLen = Math.max(...jobs.map(j => j.name.length));
const width = Math.ceil(maxNameLen * CHAR_W) + PADDING * 2 + RIGHT_MARGIN + ICON_W;
Enter fullscreen mode Exit fullscreen mode

This ensures each stage card is exactly wide enough for its longest job name: no wasted space, no text truncation. We can also implement word-aware wrapping for names that exceed a maximum width:

function wrapName(name, maxChars) {
  if (name.length <= maxChars) return name;
  // Break at spaces, hyphens, underscores
  // Join with <BR ALIGN="LEFT"/>
}
Enter fullscreen mode Exit fullscreen mode

The <BR ALIGN="LEFT"/> tag ensures each wrapped line stays left-aligned within the cell. Without the ALIGN attribute, wrapped text would center: rarely what we want.

3. Real-world showcase: CI pipeline visualization

Let's put every technique together. We want to render a GitLab CI pipeline: stages as cards, jobs as rows with status icons, and dependency edges between specific jobs.

The input: structured data

We start with a simple CSV format describing the pipeline (inspired by the output of gitlab-ci-local --list-csv):

name;stage;when;allowFailure;needs
πŸ”Ž eslint;πŸ”Ž Lint;on_success;false;
πŸ”Ž type-check;πŸ”Ž Lint;on_success;false;
πŸ“¦πŸŒ build-api;πŸ“¦ Build;on_success;false;
πŸ“¦πŸ–₯️ build-web;πŸ“¦ Build;on_success;false;
πŸ“¦βš™οΈ build-worker;πŸ“¦ Build;on_success;false;
πŸ“¦πŸ“š build-docs;πŸ“¦ Build;on_success;true;
πŸ•΅πŸŒ sonar-api;βœ… Test;on_success;false;[πŸ“¦πŸŒ build-api]
πŸ•΅πŸ–₯️ sonar-web;βœ… Test;on_success;false;[πŸ“¦πŸ–₯️ build-web]
βœ…πŸŒ unit-tests-api;βœ… Test;on_success;false;[πŸ“¦πŸŒ build-api]
βœ…πŸ–₯️ unit-tests-web;βœ… Test;on_success;false;[πŸ“¦πŸ–₯️ build-web]
β†”οΈβœ… e2e-tests;βœ… Test;manual;false;
πŸš€ deploy-staging;πŸš€ Deploy;on_success;false;
πŸš€ deploy-prod;πŸš€ Deploy;manual;false;
Enter fullscreen mode Exit fullscreen mode

Each row defines a job with its stage, trigger condition (when), failure tolerance (allowFailure), and explicit dependencies (needs).

The transformation: data to DOT

A function parses each row and builds the DOT structure programmatically:

  1. Group jobs by stage: each stage becomes a node with an HTML-label card
  2. Choose status icons: on_success β†’ βœ…, manual β†’ βš™οΈ, allowFailure: true β†’ ⚠️
  3. Calculate widths: measure job name lengths and compute per-stage column sizes
  4. Generate stage-to-stage edges: left-to-right flow between stage headers
  5. Generate needs-based edges: port-to-port connections between specific job cells
  6. Handle text wrapping: long job names word-wrapped with <BR ALIGN="LEFT"/>

Here's an excerpt of the generated DOT for the Build stage:

Build [label=<
  <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0"
         BGCOLOR="#e9ecef" STYLE="rounded">
    <TR><TD PORT="hdr" ALIGN="LEFT" CELLPADDING="8">
      <B>πŸ“¦ Build</B>
    </TD></TR>
    <TR><TD CELLPADDING="5">
      <TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="4"
             BGCOLOR="white" STYLE="rounded">
        <TR>
          <TD FIXEDSIZE="TRUE" WIDTH="25" HEIGHT="35" PORT="build_api_in">
            <IMG SRC="success.png" SCALE="TRUE"/>
          </TD>
          <TD ALIGN="LEFT" WIDTH="128" HEIGHT="35" PORT="build_api_out">
            πŸ“¦πŸŒ build-api
          </TD>
        </TR>
        <TR>
          <TD FIXEDSIZE="TRUE" WIDTH="25" HEIGHT="35" PORT="build_docs_in">
            <IMG SRC="warning.png" SCALE="TRUE"/>
          </TD>
          <TD ALIGN="LEFT" WIDTH="128" HEIGHT="35" PORT="build_docs_out">
            πŸ“¦πŸ“š build-docs
          </TD>
        </TR>
        <!-- more rows... -->
      </TABLE>
    </TD></TR>
  </TABLE>>]
Enter fullscreen mode Exit fullscreen mode

Notice how build-docs gets the warning.png icon because allowFailure is true, while regular jobs get success.png. Manual jobs get a manual.png gear icon. Each cell has both an _in port (on the icon side) and an _out port (on the name side), allowing edges to connect precisely to the correct side.

The dependency edges between jobs reference these ports:

Build:build_api_out:e -> Test:sonar_api_in:w
Build:build_api_out:e -> Test:unit_tests_api_in:w
Build:build_web_out:e -> Test:sonar_web_in:w
Build:build_web_out:e -> Test:unit_tests_web_in:w
Enter fullscreen mode Exit fullscreen mode

And the result: a complete CI pipeline diagram where stages flow left to right, jobs are listed inside their stage cards with status icons, and needs dependencies are drawn as precise connections between specific jobs:

Diagram

The rendering pipeline

There's one catch with this approach. The DOT source references local icon files (success.png, warning.png, manual.png) and uses emoji in job names. Server-side SVG rendering produces monochrome emoji: a crime against visual clarity. So the rendering pipeline needs a few extra steps:

  1. Convert SVG icons to PNG: Graphviz's <IMG> only supports raster images
  2. dot -Tsvg: compile DOT to SVG
  3. Inline images as base64: replace local <IMG> references with data URIs so the SVG becomes self-contained
  4. Chrome headless: render the SVG to PNG with proper emoji color support
  5. sharp.trim(): remove white padding around the diagram

It's a Rube Goldberg rendering pipeline, but the result is worth every layer. The diagram matches what developers see in GitLab's UI, with full-color emoji and pixel-perfect alignment.

Why Chrome? Tools like rsvg-convert or sharp render emoji as monochrome outlines (or not at all). Chrome's text rendering engine handles emoji natively, including multi-codepoint sequences like πŸ“¦πŸŒ. And --headless=new makes it usable in CI environments.

4. Integrating into your workflow

A powerful diagram technique only matters if we can integrate it into a repeatable workflow.

We've built this into the devto-cli, which processes diagram code blocks in markdown files. For standard diagram types (Mermaid, PlantUML, Graphviz, and others), it delegates rendering to Kroki. For the custom gitlab-ci format, which requires local icons and Chrome for emoji, it generates DOT locally and renders through the pipeline described above.

The workflow is straightforward:

# Write your diagram in a markdown code block, then:
dev diaggen my-article.md

# Commit the generated images and push
git add images/ && git push
dev push my-article.md
Enter fullscreen mode Exit fullscreen mode

The original diagram source stays in the markdown file. The rendered PNG is a cached build artifact, regenerated only when the diagram content changes (tracked by content checksum). Our source remains human-editable; the binary image is disposable.

We described this CLI and its other features in more detail in Dev.to Writers Community: One Command to Maintain Them All.

The key insight is that any structured data can become a pixel-perfect diagram through DOT generation. CI pipelines, database schemas, microservice topologies, deployment architectures, anything we can describe as nodes and relationships can be rendered with the precision of hand-crafted SVG, but with the maintainability of code. No dragging boxes in Lucidchart. No fighting with auto-layout. Just data in, diagram out.

Wrapping up

Graphviz's DOT language is dramatically more powerful than its reputation suggests. While most developers stop at circles and arrows, the HTML-like label syntax opens up a world of structured, styled, pixel-precise diagram components.

The key techniques to remember:

  • Nested <TABLE> elements: for card-like containers with headers and content areas
  • BGCOLOR and STYLE="rounded": for visual styling without post-processing
  • <IMG> with FIXEDSIZE: for embedding icons at exact dimensions
  • PORT attributes with compass directions: for surgical edge connections between specific cells
  • Programmatic DOT generation: to compute widths, wrap text, and handle dynamic content

Next time a diagram tool frustrates us with its auto-layout choices, remember: the engine underneath it already supports HTML tables, rounded cards, embedded icons, and port-to-port edges, all as clean, version-controlled code.

Further reading


This article was enhanced with the assistance of an AI language model to ensure clarity and accuracy in the content, as English is not my native language.

Top comments (0)