### Jamie Oaks

Evolutionary biologist.

# Getting image of TeX equation from the command line

As much as we love working in *TeX, we inevitably get stuck working in MS Office or Google Docs and have no way of making nice equations. This happened to me last fall while teaching Evolution using mostly Google Slides. Early in the semester, I found a very slick trick for quickly generating image files from TeX equations. The trick was explained in a brilliant answer by Peter Grill on StackExchange (see here).

The trick is based on a small, simple LaTeX document:

\ifdefined\formula
\else
\def\formula{E = m c^2}
\fi
\documentclass[border=2pt]{standalone}
\usepackage{amsmath}
\usepackage{varwidth}
\begin{document}
\begin{varwidth}{\linewidth}
$\formula$
\end{varwidth}
\end{document}


The standalone class and varwidth environment ensure the final image will not have unnecessary white space around your equation (see Peter Grill’s post for more details).

I saved the LaTeX code above to ~/texmf/tex/latex/formula.tex and then made sure my TeX distribution could ‘see’ it by:

$cd ~/texmf$ mktexlsr .


Depending on your system and TeX distribution, this might be a bit different.

Next, I added the following shell script, which I named formula, to my PATH:

#!/bin/sh

if [ -z "$@" ] then TEX_EQUATION="p' = \frac{p}{1-q^2s}" else TEX_EQUATION="$@"
fi

pdflatex "\def\formula{${TEX_EQUATION}}\input{formula.tex}" convert -density 300 formula.pdf -quality 90 formula.png  This could be modified to add some bells and whistles, like arguments to control the output format and quality, but I kept it simple. NOTE: convert is part of ImageMagick, so that is required for this to work. If you don’t already have ImageMagick, you should go install it right now, because it’s awesome, as I’ve talked about in previous posts Now, I can simply type $ formula "p(\theta|D) = \frac{p(D|\theta) p(\theta)}{\int p(D|\theta)p(\theta)\,d\theta}"


and get formula.png in my current working directory that has a nice looking rendition of Bayes’ rule.