Typesetting math in Medium

Using LaTeX and ImageMagick

Thai Pangsakulyanont
2 min readAug 25, 2016

Many months ago, I wrote an article about spring animation in CSS. That article involves some mathematical formulas.

I have to turn these formulas into images so that I can put it in a Medium article, and I want to make it look nice and readable on all devices.

Here are some examples:

The example equation from KaTeX demo. I have no idea what it represents.
This equation came from the article, The Fourier Transform, explained in one sentence.

The math looks crisp and sharp on desktop devices, including retina screens, and is sufficiently large on mobile devices.

Dimensions

  • On desktops, the article’s content is 700px wide. This means our image has to be 1400px wide, so that the math is crisp on retina screens.
  • On mobile, the article’s width depends on the viewport. On the web, there will be 20px margin at the left and right. Assuming 360px-wide phone, we need to fit the equation into 320px image.
  • On mobile, the text size is 18px. LaTeX’s default text size is 10pt. This means the has to be about 178pt wide.

Font

The LaTeX Code

Now, here’s the code for the LaTeX file template:

% equation.tex
\documentclass
{standalone}
\usepackage{xcolor}
\usepackage{amsmath}
\usepackage[utf8]{inputenc}
\usepackage[charter]{mathdesign}
\begin{document}
\begin{minipage}{178pt}
\begin{align*}
% Here's the equation!
f(x) = \int_{-\infty}^\infty
\hat f(\xi)\,e^{2 \pi i \xi x}
\,d\xi
\end{align*}
\end{minipage}
\end{document}

The Conversion Script

Running the LaTeX file through pdflatex produces a PDF file. imagemagick is then used to convert it into a PNG file.

pdflatex equation.texconvert -density 1200 equation.pdf \
-resize 1400 \
-gravity South -background white -splice 0x1 \
-background black -splice 0x1 \
-trim +repage -chop 0x1 \
-gravity North -background white -splice 0x1 \
-background black -splice 0x1 \
-trim +repage -chop 0x1 \
equation.png

So there you have it! If you have an idea how to make it look better, please feel free to send me a response.

--

--

Thai Pangsakulyanont

(@dtinth) A software engineer and frontend enthusiast. A Christian. A JavaScript musician. A Ruby and Vim lover.