Skip to content
Tech News
← Back to articles

Offline Math: Converting LaTeX to SVG with MathJax

read original get MathJax → more articles

Offline Math: Converting LaTeX to SVG with MathJax

Latest update: 2025-10-08 17:10:31

Pandoc can prepare LaTeX math for MathJax via its eponymous --mathjax option. It wraps formulas in <span class="math"> elements and injects a <script> tag that points to cdn.jsdelivr.net, which means rendering won't work offline or in case of the 3rd-party server failure. You can mitigate this by providing your own copy of the MathJax library, but the mechanism still fails when the target device doesn't support JavaScript (e.g., many epub readers).

At the same time, practically all browsers support MathML. Use it (pandoc's --mathml option), if you care only about the information superhighway: your formulas will look good on every modern device and scale delightfully. Otherwise, SVGs are the only truly portable option.

Now, how can we transform the html produced by

$ echo 'Ohm'\''s law: $I = \frac{V}{R}$.' | pandoc -s -f markdown --mathjax

into a fully standalone document where the formula gets converted into SVG nodes?

Use an html parser like Nokogiri, and replace each <span class="math"> node with an image. There are multiple ways to convert a TeX-looking string to an SVG: using MathJax itself (which provides a corresponding CLI example), or by doing it in a 'classical' fashion with pdflatex. (You can read more about this method in A practical guide to EPUB, chapters 3.4 and 4.6.)

Alternatively, load the page into a headless browser, inject MathJax scripts, and serialise the modified DOM back to html.

I tried the 2nd approach in 2016 with the now-defunct phantomjs. It worked, but debugging was far from enjoyable due to the strangest bugs in phantomjs. I can still run the old code, but it depends on an ancient version of the MathJax library that, for obvious reasons, isn't easily upgradable within the phantomjs pre-es6 environment.

... continue reading