# Scale text/formula to fit area preserving aspect ratio

I would like write a command to scale a given text-object to fit into a given area preserving the aspect ratio. That is, a maximum width and height should not be exceeded, but either width or height of the text should fit the given value. The following would not work because the maximum height could be exceeded:

\resizebox{\mywidth}{!}{#1}


Likewise, the following can exceed a maximum width:

\resizebox{!}{\myheight}{#1}

• The adjustbox package does this. Oct 4, 2015 at 18:10

You can do it with adjustbox, the trick is to scale up the contents so it needs to be scaled down.

\documentclass{article}
\usepackage{amsmath}

\newlength{\myheight}
\newlength{\mywidth}
\setlength{\myheight}{3cm}
\setlength{\mywidth}{6cm}

% A box for displaying the result
\newsavebox{\FRAME}
\sbox\FRAME{%
\setlength{\fboxsep}{0pt}%
\kern-\fboxrule
\fbox{\rule{\mywidth}{0pt}\rule{0pt}{\myheight}}%
\kern-\mywidth\kern-\fboxrule
}

\begin{document}

\usebox{\FRAME}%
\raisebox{\depth}{%
$\displaystyle \int_{-\infty}^{\infty}e^{-x^{2}}\,dx=\sqrt{\pi}$%
}%
}

\bigskip

\usebox{\FRAME}%
$\displaystyle \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ 0 & 0 \\ 0 & 0 \end{bmatrix}$%

I used \usebox{\FRAME} just for showing the intended area to fill. It's also necessary to raise the box by its depth, or it would stick below the area.