← main page

Generating TeX formulas in images

, 09 April 2012

The article is generally just a note, may help anyone someday.

How to

The following example uses standard console commands latex and dvipng, which can be installed in ubuntu from packages tex-common and dvipng respectively.

TEX_TEMPLATE defines custom TeX commands if needed:


The main code:

import os
from tempfile import mkdtemp

from somewhere import TEX_TEMPLATE

DVIPNG_COMMAND = 'dvipng -T tight -x 1200 -z 9 -bg transparent %s.dvi -o %s.png'
LATEX_COMMAND = 'latex -halt-on-error %s.tex'

# ...

workdir = mkdtemp()

filename = 'formula'

with open(filename + '.tex', 'w') as tex_file:
    tex_file.write(TEX_TEMPLATE % '$ \sin x $')

os.system(LATEX_COMMAND % filename)
os.system(DVIPNG_COMMAND % (filename, filename))

P.S. Python itself has nothing to do with the subject, nevertheless I've included an example in Python, just in case.

comments powered by Disqus
Tags: python, TeX, note
Digital Ocean