[Tex/LaTex] TeX to image over command line

conversionmac

I'd like to generate an image with math formulas with TeX from command line. Something like:

$ tex-executable "E=\frac{m_1v^2}{2}" e2.png

I have MacTex 2009 installed and I'm pretty sure that something like that already exists in this distribution. If not please suggest me a tool.

Best Answer

Update: 2012-01:

The standalone class now has a varwidth option, so with the current release, one would simply use the [varwidth] package option:

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

Save the following as formula.tex:

\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 is used for cropping. The varwidth environment is similar to the minipage environment, but sets its width to match the narrower natural width based on the content.

The ifdefined...\fi is only necessary so that this file can be compiled by itself, which is useful to test to ensure that there are no errors in it, in case you decide to make changes to it.

Then you can process this file as:

pdflatex "\def\formula{E=\frac{m_1v^2}{2}}\input{formula.tex}"
convert -density 300 formula.pdf -quality 90 formula.png

where convert is part of ImageMagick. This yields the following PNG file:

enter image description here

I have not used it, but the current development version of standalone can generate the PNG directly if you use

\documentclass[convert={density=300,size=1080x800,outext=.png}]{standalone}

Alternatively you could also use GIMPas per this link from Wikibooks.

Related Question