# Generate an image with minimum space around it

I'm using this solution to generate images:

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


Everything works perfect when I have a large multi-level formula, say something like this pV=\frac{m}{M}RT.

However, when the formula gets more flat, like p=mv, I get extra space at the top. Looks like the document has some kind of a min height … How do I remove it? So that the resulting img/pdf will be exactly the size of my formula + border?

The space comes from \baselineskip, inserted by the displayed equation.

The following example does not use $...$, but simulates it via inline math and setting \displaystyle:

\ifdefined\formula
\else
\def\formula{p=mv}
\fi
\documentclass[border=2pt]{standalone}
\usepackage{amsmath}
\usepackage{varwidth}
\begin{document}
\begin{varwidth}{\linewidth}
$\displaystyle\formula$%
\end{varwidth}
\end{document}