Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a latex code to mathml or svg code in python

Is there any python code that allow take a latex code (for equations) and parse it to mathml or svg code ? A simple function that take as argument a string (the latex code) and output a string (the svg or mathml code) would be perfect.

PS. I've found this http://svgkit.sourceforge.net/SVGLaTeX.html but it's a web based project and not sure how to use it.

EDIT: or in any language (not obligatory python), or at least an exe file that can be simply executed by a command line to do that (without installing additional stuff).

like image 510
shn Avatar asked Mar 06 '12 16:03

shn


2 Answers

You can do this without installing anything:

import urllib
import urllib2

def latex2svg(latexcode):
    """
    Turn LaTeX string to an SVG formatted string using the online SVGKit
    found at: http://svgkit.sourceforge.net/tests/latex_tests.html
    """
    txdata = urllib.urlencode({"latex": latexcode})
    url = "http://svgkit.sourceforge.net/cgi-bin/latex2svg.py"
    req = urllib2.Request(url, txdata)
    return urllib2.urlopen(req).read()

print latex2svg("2+2=4")
print latex2svg("\\frac{1}{2\\pi}")

This script calls the SVGKit server you mention, which does the work of converting LaTeX to SVG. It returns the text of SVG (try it out).

Note that, as with any solution that relies on third-party web apps,

  1. This assumes you have a reliable internet connection

  2. Its performance depends on the speed of your connection and of the server

  3. This relies on the third-party site to stay consistent (if they take it down, or the format significantly changes, this will no longer work without adjustment)

like image 189
David Robinson Avatar answered Oct 15 '22 11:10

David Robinson


My solution is to use latex to generate a DVI file and then use dvisvgm to convert the dvi to svg:

  1. latex file.tex # produces file.dvi
  2. dvisvgm --no-fonts file.dvi file.svg # --no-fonts: use SVG paths only

In my experience, the final svg is rendered exactly as wanted (with InkScape, or QSvgRenderer).

The LaTeX template I use is this:

\documentclass[paper=a5,fontsize=12pt]{scrbook}
\usepackage[pdftex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{tikz}
\begin{document}
\begin{preview}
\begin{tikzpicture}[inner sep=0pt, outer sep=0pt]
\node at (0, 0) {texCode}; % <--Put your tex-code here
\end{tikzpicture}
\end{preview}
\end{document}
like image 42
dhaumann Avatar answered Oct 15 '22 10:10

dhaumann