[Tex/LaTex] how to get mathematical equations into image in latex


how to get mathematical equations into image in latex? I want the code that convert all equations into image in the pdf file after compile the tex file.

Best Answer

I suppose you could write a package that compiles equations in subjobs, like so (call this package imageeqn.sty):

\ProvidesPackage{imageeqn}[2014/11/30 v0.1 Image equations]



\begingroup \catcode `|=0 \catcode `[=1
\catcode`]=2 \catcode `\{=12 \catcode `\}=12
\catcode`\\=12 |gdef|@ximageeqn#1\end{imageeqn}[|immediate|write|@out[#1]|end[imageeqn]]

\def\imageeqn{\kernel@ifnextchar [{\@imageeqn}{\@imageeqn[]}}

\begingroup \catcode`\^^M=12 %

\immediate\write18{pdflatex --enable-write18 -interaction=nonstopmode \jobname-eqn-\arabic{imageeqn}.tex}

This package (which I wrote by modifying python.sty) defines an environment imageeqn, which takes the equation inside of it, generates a tex file, compiles it to png, and then includes the resulting png using \includegraphics. This can be used as follows (let's call this file image.tex):



Pythagorean theorem:
\begin{imageeqn}x^2 + y^2 = z^2.\end{imageeqn}
Some integral:
\begin{imageeqn}\Gamma(t) = \int_0^\infty x^{t-1} e^{-x} \, dx.\end{imageeqn}

Compile this with the command line:

pdflatex --enable-write18 image.tex

The result is a pdf file that has the two equations embedded as rasterized images. I'm not sure why you would ever want to do this, but I enjoyed myself trying to figure out how to do this anyway :)

This implementation is pretty limited by the way: first of all, it won't compile if you put \end{imageeqn} on a new line. Second of all, it turns equations into text-style math (in dollar signs), so equation numbering, aligning, etc., are not supported.

Solving the newline problem

The first problem can be fixed, at least on Linux, by preprocessing the subjobs with sed. This can be done by replacing:

\immediate\write18{pdflatex --enable-write18 -interaction=nonstopmode \jobname-eqn-\arabic{imageeqn}.tex}

in the above code by:

\immediate\write18{sed -i '/^$/d' \jobname-eqn-\arabic{imageeqn}.tex; pdflatex --enable-write18 -interaction=nonstopmode \jobname-eqn-\arabic{imageeqn}.tex}

Using preprocessing to make \[, \begin{equation} work

Making \[, \], \begin{equation}, \end{equation} work can be done by preprocessing the input with sed:

cat input.tex | sed 's|\\\[|\begin{imageeqn}|g' \
              | sed 's|\\\]|\end{imageeqn}|g' \
              | sed 's|\\begin{equation}|\begin{imageeqn}|g' \
              | sed 's|\\end{equation}|\end{imageeqn}|g' \
              > input2.tex
pdflatex --enable-write18 input2.tex

Perhaps lualatex may be of help here, but I don't know anything about that.

Related Question