maccha
Render Mermaid diagrams to SVG or PNG from Python. The renderer is written in Rust and compiled into the package: no browser, no Node.js, no other Python dependencies.
pip install maccha
It supports Python 3.9 and newer. One wheel per platform (Linux, macOS and Windows) serves every Python version.
Use it
import maccha
svg = maccha.render_svg("flowchart LR; A-->B-->C") # str
png = maccha.render_png("flowchart LR; A-->B-->C", scale=2) # bytes
dark = maccha.render_png("flowchart LR; A-->B", theme="dark", background="#1e1e1e")
open("out.svg", "w", encoding="utf-8").write(svg)
open("out.png", "wb").write(png)
Every argument after the diagram source is keyword-only:
| Argument |
Applies to |
Meaning |
theme |
both |
None (default), "default", "dark", "forest", "neutral" or "modern". Like mmdr -t: None leaves the theme to config["theme"], then to the built-in default; a name wins over config. |
config |
both |
A dict like the JSON file given to mmdr -c (theme, themeVariables, flowchart, ...). A diagram's own %%{init}%% wins over it. |
fonts |
both |
A maccha.Fonts(system=True, files=[], dirs=[], data=[]) to add fonts, or to ignore the system's (system=False) |
strict_fonts |
both |
Raise RenderError if some text has no font that covers it |
scale |
PNG |
Pixels per SVG unit; default 2.0 |
background |
PNG |
A hex color: "#ffffff" (#rgb, #rrggbb or #rrggbbaa; "#00000000" is transparent). Names such as "white" raise RenderError. Default is the theme's background. |
For the same diagram, render_svg returns exactly what mmdr -e svg writes, and render_png(src, scale=1.0) what mmdr -e png writes.
Errors and warnings
try:
maccha.render_svg("flowchart LR; A--")
except maccha.MermaidSyntaxError as e: # a ValueError
print(e.line, e.col, e.message) # 1-based; col is 0 if unknown
MermaidSyntaxError: the diagram is not valid. It has line, col and message.
RenderError: any other failure, such as strict_fonts=True with missing glyphs.
MissingGlyphWarning: a UserWarning raised through warnings.warn when some text has no font that covers it.
The GIL is released while a diagram renders, so threads can render in parallel.
Fonts
A Noto Sans Khmer font (SIL Open Font License 1.1) is built in, so Khmer text renders with no font installed. For Japanese, Chinese, Korean or Thai text, the machine needs a font that covers it, or pass one with Fonts(files=[...]).
SVGs name their fonts but do not embed them; PNGs are drawn with the fonts that were measured.
Links
MIT license. The bundled font's license is included in the wheel.