Search code examples
latexpdflatexxelatex

Generating LaTeX Server Side


I'm trying to build a service that accepts some string with LaTeX formatting and then returns a string with the LaTeX bits as pngs, or whatever else.

So, the idea is:

client sends a request containing: the point is that $sum_{n=1}^5 f(x)$ is a good estimate

server sends back the string: the point is that FORMULAS_HERE is a good estimate

I really have no idea where to begin getting the LaTeX converted. Naively, I assume I would just parse out the LaTeX bits and then do something to get a png/jpeg/etc... and then insert that into the response.

Googling around really reveals minimal information.

Currently, my simple server is built on node, but that's not really important. I can change languages if there's some magic solution out there. I honestly wish I could magically transform LaTeX into unicode and have it be perfectly seamless.

Question: How do I handle LaTeX on the server side? - The goal is to then spit it back to the client so the text can be inlined relatively naturally (i.e. I could text my buddy Hey, what if $\chi(n)$ was considered independently? and it would be received formatted on the other end without begin a weird big picture blob).

Any advice on just a direction or set of packages/technologies/etc.. would be useful here.


Solution

  • Prepare your latex document with math and convert it using the excellent open-source ImageMagick

    pdflatex formula.tex
    convert -density 300 formula.pdf -quality 90 formula.png
    

    The convert command used above is one of the ImageMagick tools. See documentation and numerous online resources for many options. The software has versions for all major platforms.

    The input latex file should be prepared so that there is no background, margins, etc. For discussion of how to do that, see this post, and the source for it. The example above ultimately comes from there.

    This is one way to write the formula.tex file used above, from the linked source.

    \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}
    

    There are other converters out there but you need not bother if you can use this.


    I have to mention MathJax. It runs in a browser, via one-line JavaScript snippet. Should you ever migrate to a browser/mobile service this would be a perfect solution. Here is their one page tutorial.