latex2svg

Python wrapper and CLI utility to render LaTeX markup and equations as SVG using
dvisvgm and svgo.

Based on the original work by Tino Wagner, this version has enhanced features.

The design goals are:

  • Auto vertical alignment without any further styling.
    • by adding a style="vertical-align:" to the SVG attributes
  • Auto scaling on font size/zoom change.
    • by using em units for width, height and style
  • Unique IDs so multiple SVGs on one page won’t corrupt each other.
    • by generating random 4-character ID prefixes within the SVG
  • Minified SVG for direct inclusion.
    • by using svgo (a Node app)
  • For e-book readers and dictionaries:
    • Good legibility.
    • Direct inclusion as <svg>, not necessarily <img>.
    • Possibility for easy CSS styling, i.e. using fill.
    • Compatibility with pyglossary and the ebook-reader-dict project.
    • Possibility of LaTeX preamble changes/additions, to correct LaTeX code in automated processes like converting a Wiktionary dump to an e-reader dictionary.

Usage

Python 3 module

from latex2svg import latex2svg
out = latex2svg(r'$\sin(x) = \sum_{n=0}^{\infty} \dots$')
print(out['valign'])  # baseline position in em
print(out['svg'])  # rendered SVG

CLI utility

$ ./latex2svg.py --help
usage: latex2svg.py [-h] [--version] [--preamble PREAMBLE]

Render LaTeX code from stdin as SVG to stdout. Writes metadata (baseline
position, width, height in em units) into the SVG attributes.

optional arguments:
  -h, --help           show this help message and exit
  --version            show program's version number and exit
  --preamble PREAMBLE  LaTeX preamble code to read from file

$ echo '$\sin(x) = \sum_{n=0}^{\infty} \dots$' | ./latex2svg.py > sample.svg

Result:

sample formula

Requirements

  • Python 3
  • A working LaTeX installation, like Tex Live or MacTeX
  • dvisvgm
  • svgo

License

This project is licensed under the MIT license. See LICENSE for
details.

Copyright © 2022 Matthias C. Hormann