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

Viewed 20178

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?

7 Answers

This is a bit ugly solution I often use, but I found it easiest to use in many cases.

import matplotlib.pyplot as plt
import io
from PIL import Image, ImageChops

white = (255, 255, 255, 255)

def latex_to_img(tex):
    buf = io.BytesIO()
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    plt.axis('off')
    plt.text(0.05, 0.5, f'${tex}$', size=40)
    plt.savefig(buf, format='png')
    plt.close()

    im = Image.open(buf)
    bg = Image.new(im.mode, im.size, white)
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    return im.crop(bbox)

latex_to_img(r'\frac{x}{y^2}').save('img.png')

Keep in mind, it requires pillow and matplotlib.

pip install matplotlib pillow
Related