-3

I'd like to print LaTeX mathmode formulas to images (preferable without saving to hard disk) in Python. I already found matplotlib but it seems one can't dynamically shrink the size of the image to the size of the formula which is what I need.

It would be nice if someone had an example how to accomplish such a thing.

m7x
  • 1
  • 1
  • Have you looked for examples of how to accomplish this? Rendering LaTex: http://stackoverflow.com/questions/1381741/converting-latex-code-to-images-or-other-displayble-format-with-python Resizing in Matplotlib: http://stackoverflow.com/questions/332289/how-do-you-change-the-size-of-figures-drawn-with-matplotlib – kbshimmyo Apr 29 '17 at 17:48
  • Already read the second link, but as far as I have seen there isn't a method to get the width of the formula so it doesn't help much. On the other hand I only read till response #1 in the first link before, my fault, and then stoped reading because it only said what I knew before. I therfore missed the sympy answer which seems useful in my case. Thanks alot. – m7x Apr 29 '17 at 17:59

1 Answers1

2

In LaTeX, use the standalone package.

Create a LaTeX file with the math in it.

\documentclass{standalone}
\begin{document}
$\displaystyle I = \int_0^h y^2\mathrm{d}A$
\end{document}

Convert that to pdf:

pdflatex eqn.tex

Convert the pdf to an image (for example using the ImageMagick tools).

convert -density 300 -units PixelsPerInch eqn.pdf eqn.png

(There are multiple ways of converting LaTeX output to image format. You could also use plain latex and dvipng.)

This results in:

example

Running the commands can be done with the subprocess module.

Edit: Changed to use \displaystyle, which looks much nicer than inline math.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • That answer seems much better than that sympy solution (see comments above). Thank you. – m7x Apr 29 '17 at 18:07