How to Integrate graphviz2drawio into Other Python Projects

You can integrate graphviz2drawio into Python projects by importing the convert() function from graphviz2drawio.graphviz2drawio, which accepts DOT files, strings, file objects, or pygraphviz.AGraph instances and returns draw.io-compatible XML.

The hbmartin/graphviz2drawio library converts Graphviz DOT diagrams into editable draw.io diagrams. Whether you're building documentation pipelines, diagram generators, or automation tools, you can integrate graphviz2drawio into other Python projects using its clean public API.

Understanding the graphviz2drawio Architecture

The library exposes a single public entry point: the convert() function in graphviz2drawio/graphviz2drawio.py. This function orchestrates a six-stage pipeline:

  1. Input normalization – The helper _load_pygraphviz_agraph() converts file paths, strings, or file objects into a pygraphviz.AGraph instance.
  2. Graph extraction – Node and edge attributes are extracted into dictionaries (graph_nodes, graph_edges).
  3. SVG rendering – The AGraph renders to SVG via Graphviz's graph.draw(..., format="svg").
  4. SVG parsinggraphviz2drawio/models/SvgParser.py extracts nodes, edges, and clusters from the SVG, handling gradients and edge labels.
  5. Model enrichment – Parsed objects are merged with original Graphviz attributes.
  6. mxGraph generationgraphviz2drawio/mx/MxGraph.py generates the final draw.io XML.

Because the entire pipeline is encapsulated in convert(), you only need to import and call one function to integrate graphviz2drawio into your codebase.

Installation and Dependencies

Install the library via pip:

pip install graphviz2drawio

This installs pygraphviz and other Python dependencies automatically. However, you must install the Graphviz system binaries (dot) separately—see the repository README for platform-specific instructions.

Required dependencies include:

  • pygraphviz – Python bindings for Graphviz and the AGraph class.
  • svg.path – Used internally for parsing SVG path data in graphviz2drawio/mx/Curve.py.
  • Standard libraryxml.etree.ElementTree, pathlib, re, and io.

Using the Public API to Integrate graphviz2drawio

The convert() function accepts four input types, making it flexible for different integration scenarios.

Converting DOT Files from Disk

Pass a file path as a string or Path object:

from graphviz2drawio import graphviz2drawio

xml_output = graphviz2drawio.convert("diagram.dot")
print(xml_output)  # Valid draw.io XML

You can specify an alternative layout engine (e.g., neato, fdp) via the layout_prog parameter:

xml_output = graphviz2drawio.convert("diagram.dot", layout_prog="neato")

Converting Raw DOT Strings

For dynamically generated diagrams, pass the DOT source directly as a string:

dot_source = """
digraph Network {
    rankdir=LR;
    Server -> Client [label="request"];
    Client -> Database [label="query"];
}
"""
xml = graphviz2drawio.convert(dot_source)

Working with pygraphviz.AGraph Objects

If your application already uses pygraphviz, pass an AGraph instance directly to avoid serialization overhead:

from pygraphviz import AGraph
from graphviz2drawio import graphviz2drawio

graph = AGraph(directed=True)
graph.add_edge("Node1", "Node2", color="blue", penwidth=2)
graph.add_edge("Node2", "Node3", style="dashed")

xml = graphviz2drawio.convert(graph, layout_prog="dot")

Processing File-Like Objects

For web applications or streaming pipelines, pass a file-like object such as io.StringIO:

import io
from graphviz2drawio import graphviz2drawio

dot_stream = io.StringIO("digraph { a -> b -> c }")
xml = graphviz2drawio.convert(dot_stream)

Embedding graphviz2drawio in Larger Applications

When building documentation generators or CI/CD pipelines, wrap the converter in utility functions:

from pathlib import Path
from graphviz2drawio import graphviz2drawio

def render_diagram(dot_path: str, output_path: str, layout: str = "dot") -> None:
    """
    Convert a Graphviz DOT file to a draw.io XML file.
    
    Args:
        dot_path: Path to the input .dot or .gv file
        output_path: Path where the .xml file will be written
        layout: Graphviz layout engine (dot, neato, fdp, sfdp, twopi, circo)
    """
    xml_content = graphviz2drawio.convert(dot_path, layout_prog=layout)
    
    Path(output_path).write_text(xml_content, encoding="utf-8")
    print(f"Converted {dot_path} -> {output_path}")

# Batch processing example

if __name__ == "__main__":
    for dot_file in Path("diagrams/").glob("*.dot"):
        render_diagram(str(dot_file), str(dot_file.with_suffix(".xml")))

This pattern handles error boundaries, batch operations, and custom output formatting while leveraging the single convert() entry point.

Key Source Files for Advanced Integration

For developers extending or debugging the integration, these files define the public interface and internal pipeline:

File Purpose
graphviz2drawio/graphviz2drawio.py Contains the public convert() function and _load_pygraphviz_agraph() helper for input normalization.
graphviz2drawio/mx/MxGraph.py Generates the final draw.io XML from enriched model objects.
graphviz2drawio/models/SvgParser.py Parses SVG output from Graphviz to extract nodes, edges, and clusters.
graphviz2drawio/__main__.py CLI entry point; useful reference for argument handling.

Summary

  • Single entry point: Import convert() from graphviz2drawio.graphviz2drawio to integrate the library.
  • Flexible inputs: Pass file paths, DOT strings, pygraphviz.AGraph objects, or file-like streams.
  • Zero configuration: The function handles SVG rendering, parsing, and XML generation internally.
  • Dependencies: Requires pygraphviz and system Graphviz binaries; install via pip install graphviz2drawio.
  • Extensible: Access internal modules like MxGraph.py or SvgParser.py for custom conversion pipelines.

Frequently Asked Questions

What input formats does graphviz2drawio support when used as a library?

The convert() function accepts four input types: a file path (string or Path), a raw DOT source string, a file-like object (such as io.StringIO), or a pygraphviz.AGraph instance. The internal _load_pygraphviz_agraph() helper normalizes all inputs into an AGraph object before processing.

Do I need to install Graphviz separately when integrating graphviz2drawio?

Yes. While pip install graphviz2drawio installs the Python dependencies (including pygraphviz), the Graphviz system binaries—specifically the dot executable—must be installed separately on your operating system. The library invokes Graphviz via pygraphviz to render SVG intermediate files.

Can I customize the layout engine when using the Python API?

Yes. The convert() function accepts a layout_prog parameter that defaults to "dot" but supports any Graphviz layout engine such as "neato", "fdp", "sfdp", "twopi", or "circo". Pass this argument when calling convert() to control the diagram layout algorithm.

Is graphviz2drawio suitable for batch processing multiple diagrams?

Yes. Because the convert() function is stateless and accepts file paths or strings, you can call it repeatedly in loops or list comprehensions to process batches of DOT files. For production use, wrap the call in error handling to manage malformed DOT syntax or missing files gracefully.

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 →