Scale an equation to fit exact page width
I just had the situation that I wanted this only for lines exceeding \linewidth
, that is: Squeezing long lines slightly.
Since it took me hours to figure this out, I would like to add it here.
I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g.
multline
of themathtools
package). So use it conscious.
In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.
\usepackage{environ} % provides \BODY
\usepackage{etoolbox} % provides \ifdimcomp
\usepackage{graphicx} % provides \resizebox
\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation
\RenewEnviron{equation}{
\settowidth{\myl}{$\BODY$} % calculate width and save as \myl
\origequation
\ifdimcomp{\the\linewidth}{>}{\the\myl}
{\ensuremath{\BODY}} % True
{\resizebox{\linewidth}{!}{\ensuremath{\BODY}}} % False
\origendequation
}
Before After
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}