How to Use the graphviz2drawio Library Programmatically in Python

The graphviz2drawio library exposes a single convert() function that transforms Graphviz DOT files, strings, or pygraphviz.AGraph objects into draw.io-compatible XML through a three-stage pipeline of loading, SVG parsing, and mxGraph generation.

The hbmartin/graphviz2drawio repository provides a lightweight Python interface for converting Graphviz diagrams into the XML format used by draw.io (diagrams.net). Whether you are batch-processing diagrams or integrating graph visualization into a web application, you can use the graphviz2drawio library programmatically to automate this transformation without invoking command-line tools.

Understanding the Conversion Pipeline

The conversion process implemented in graphviz2drawio/graphviz2drawio.py follows three distinct stages to ensure accurate translation of visual and structural graph elements.

Loading Graphviz Input

The private helper _load_pygraphviz_agraph (lines 52-78 in graphviz2drawio/graphviz2drawio.py) accepts multiple input types—file paths, file-like objects, raw DOT strings, or existing pygraphviz.AGraph instances—and normalizes them into a canonical AGraph object.

Rendering and SVG Parsing

Once loaded, the graph is rendered to SVG using graph.draw(..., format="svg"). The parse_nodes_edges_clusters function (lines 23-38 in models/SvgParser.py) walks the SVG DOM to extract nodes, edges, clusters, and their visual attributes, creating internal model objects (Node, Edge, Cluster).

Building the mxGraph Model

The extracted model objects are passed to the MxGraph class (lines 14-50 in mx/MxGraph.py), which assembles the final XML document in the draw.io (mxGraph) format. Calling MxGraph.value() returns the complete XML string ready for import.

Programmatic Usage Examples

The public API consists of the convert() function, which orchestrates the entire pipeline. Below are practical implementations for common input scenarios.

Convert from File Path

from graphviz2drawio import graphviz2drawio

xml = graphviz2drawio.convert("examples/hello.dot")
print(xml)  # XML string ready for draw.io import

Using Path Objects or File Handles

from pathlib import Path
from graphviz2drawio import graphviz2drawio

path = Path("examples/network.gv")
with path.open() as f:
    xml = graphviz2drawio.convert(f)  # file-like object accepted

Convert Raw DOT Strings

dot = """
digraph G {
    A -> B [label="edge"]
    B -> C
}
"""
xml = graphviz2drawio.convert(dot)  # string auto-detected

Convert Existing pygraphviz AGraph Objects

from pygraphviz import AGraph
from graphviz2drawio import graphviz2drawio

g = AGraph()
g.add_edge("X", "Y")
xml = graphviz2drawio.convert(g)  # already an AGraph

Handling Conversion Errors

If Graphviz cannot render the SVG or the input is malformed, the library raises UnableToParseGraphError (defined in models/Errors.py, lines 9-16). This domain-specific exception allows robust error handling in production workflows.

from graphviz2drawio import graphviz2drawio
from graphviz2drawio.models.Errors import UnableToParseGraphError

try:
    xml = graphviz2drawio.convert("broken.dot")
except UnableToParseGraphError as e:
    print(f"Conversion failed: {e}")

Saving Output for draw.io

The returned XML string can be written directly to a file with the .drawio or .xml extension for immediate import into draw.io.

from pathlib import Path

xml = graphviz2drawio.convert("mygraph.gv")
Path("mygraph.drawio.xml").write_text(xml, encoding="utf-8")

Summary

  • The convert() function in graphviz2drawio/graphviz2drawio.py provides the primary entry point for all transformations.
  • Input flexibility: accepts file paths, file-like objects, raw DOT strings, or pygraphviz.AGraph instances via _load_pygraphviz_agraph.
  • The three-stage pipeline loads the graph, parses the SVG representation via models/SvgParser.py, and generates mxGraph XML via mx/MxGraph.py.
  • Always wrap conversion calls in try/except blocks to catch UnableToParseGraphError from models/Errors.py.
  • Output is a standard XML string compatible with draw.io (diagrams.net) import.

Frequently Asked Questions

What input formats does graphviz2drawio support?

The library accepts four input types: string file paths, pathlib.Path objects, file-like objects (open handles), raw DOT syntax strings, or pre-instantiated pygraphviz.AGraph objects. The internal _load_pygraphviz_agraph function automatically detects and normalizes these into an AGraph instance.

How does graphviz2drawio handle complex Graphviz features like clusters?

The parse_nodes_edges_clusters function in models/SvgParser.py explicitly walks the SVG output to identify clusters, nodes, and edges along with their visual styling. These elements are preserved as distinct Cluster, Node, and Edge model objects before being serialized into the mxGraph format.

Can I use graphviz2drawio in a web application or API?

Yes. Since the convert() function operates entirely in-memory and returns a string, you can integrate it into Flask, FastAPI, or Django endpoints. Pass the DOT data directly as a string, catch UnableToParseGraphError for validation, and return the XML string to clients for client-side rendering in draw.io.

Is there a command-line interface available?

While this article focuses on programmatic usage, the repository includes a CLI entry point in graphviz2drawio/__main__.py. This module wraps the same convert() function described here, making it available for shell scripting and batch operations when Python integration is not required.

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 →