← 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:

TEX_TEMPLATE = r'''
\documentclass{article} 
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{bm}
\DeclareMathOperator{\tg}{tg}
\DeclareMathOperator{\ctg}{ctg}
\pagestyle{empty} 
\begin{document} 
%s
\end{document}
'''

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()
os.chdir(workdir)

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