Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting latex code to Images (or other displayble format) with Python

Tags:

I have a function I am consuming that returns a string of latex code. I need to generate an image from this. Most of the methods I have seen for doing so suggest calling an external application via say the subprocess module which will generate the image for me.

However, management is not keen on this as it will require external users to install additional software in addition to our own which, with our user base, is not something we can assume to be a simple task.

So are there any python libraries that will accomplish the task of taking latex into a format (such as an image file) which is displayable in a GUI?

like image 796
Mark Roddy Avatar asked Sep 04 '09 22:09

Mark Roddy


People also ask

Can I use LaTeX in Python?

PyLaTeX is a Python library for creating and compiling latex documents. The goal of this library is to be easy but is also to provide an extensible interface between Python and latex. Some features of pylatex are: We can access all the features of LaTeX in python using this module.


1 Answers

SymPy has a builtin preview function that does this.

expr = sin(sqrt(x**2 + 20)) + 1 preview(expr, viewer='file', filename='output.png') 

generates

enter image description here

There are lots of options to preview to change the format of the output (for instance, if you don't like the Euler font you can set euler=False).

preview also accepts a LaTeX string instead of a SymPy expression if you have that

preview(r'$$\int_0^1 e^x\,dx$$', viewer='file', filename='test.png', euler=False) 

enter image description here

like image 189
asmeurer Avatar answered Sep 22 '22 13:09

asmeurer