[Tex/LaTex] Fit float to page

floatsscaling

This is a follow-up question to Best figure size adjustment when dealing with different image sizes.
I want to resize a figure in a way, that the figure including the caption fits the page. Resizing just the figure has been explained in the previously mentioned question. The solution looked as follows:

\documentclass[a4paper,10pt]{scrartcl}  
\usepackage{graphicx}  
\begin{document}  
\begin{figure}  
\centering  
\includegraphics[width=\textwidth,height=\textheight]{AnyGraphic}  
\caption{Some random caption. This should be long enough to create at least one line break, as the overall size of the float naturally depends on the size of the caption}  
\end{figure}  
\end{document}

Without the caption, everything is fine. But including a caption will result in a Float too large for page warning.
Thus the question: How can I fit a float including the caption to a page?
Note: I want to do this for many floats with captions of different lengths. I would thus prefer a solution that works for captions of arbitrary lengths.

Best Answer

If you use both width and height then you also almost always want to use keepaspectratio otherwise the image will be distorted to match the specified dimensions. For the rest you can do something like:

\documentclass[a4paper,10pt]{scrartcl}  
\usepackage{graphicx}  
\begin{document}  
\begin{figure}  
\centering  

\includegraphics[width=\textwidth,height=\dimexpr\textheight-4\baselineskip-\abovecaptionskip-\belowcaptionskip\relax,
keepaspectratio]{ug}  
\caption{Some random caption. This should be long enough to create at least one linebreak, as the overall size of the float naturally depends on the size of the caption}  
\end{figure}  
\end{document}

Or you could measure the caption. I would get a warning that the float is too large by 0.04385pt which looks suspiciously like the depth, but rather than worry about that I just subtracted an extra 2pt for luck. keepaspectratio is commented out so that my test image stretches in this direction.

\documentclass[a4paper,10pt]{scrartcl}  
\usepackage{graphicx} 
\newsavebox\cpsave 
\begin{document}  
\begin{figure}  
\centering  
\savebox\cpsave{\begin{minipage}{\textwidth}\vspace*{\abovecaptionskip}%
\caption{Some random caption. This sholud be long enough to create at least one linebreak, as the overall size of the float naturally depends on the size of the caption}\end{minipage}}

\includegraphics[width=\textwidth,height=\dimexpr\textheight-\ht\cpsave-\dp\cpsave-\lineskip-2pt\relax,
%keepaspectratio
]{ug}  

\noindent\usebox\cpsave
\end{figure}  
\end{document}
Related Question