Render LaTeX to SVG with matplotlib backend

Published

April 4, 2023

We use matplotlib’s mathtext system and SVG backend to generate an SVG rendering of LaTeX code.

from matplotlib.backends.backend_svg import RendererSVG
from matplotlib.font_manager import FontProperties
from io import StringIO
from IPython.display import display_html
fp = FontProperties()

s = r"$D^{\ast\ast}\ell\nu$"

# get bounding box of rendered text
r = RendererSVG(0, 0, StringIO())
w, h, _ = r.get_text_width_height_descent(s, fp, ismath=True)

with StringIO() as f:
    # render LaTeX as path
    r = RendererSVG(w, h, f)
    r.draw_text(r.new_gc(), 0, h, s, fp, angle=0, ismath=True)
    f.seek(0)
    svg_code = f.read()

display_html(svg_code, raw=True)
2024-05-13T09:44:49.847495 image/svg+xml Matplotlib v3.8.4, https://matplotlib.org/

We can insert the SVG image into HTML layouts, for example, into an HTML table.

display_html(f"""
<html>
<body>
<table>
<tr>
    <td> {svg_code} </td> <td> foo </td>
</tr>
<tr>
    <td> bar </td> <td> baz </td>
</tr>
</table>
</body>
</html>
""", raw=True)
2024-05-13T09:44:49.847495 image/svg+xml Matplotlib v3.8.4, https://matplotlib.org/ foo
bar baz