1

I want to measure the height of a caption, by typesetting into a \savebox, but run into

You can't use `\hrule' here except with leaders.

The offending line in the MWE below is commented out.

Code

\documentclass{article}
\usepackage{caption}
\usepackage{graphicx}

\newsavebox{\CaptionSavebox}
\captionsetup{width=0.20\linewidth}%

\newcommand*{\CaptionText}{This is a caption for the above figure}

\begin{document}
\begin{figure}
    %\savebox{\CaptionSavebox}{\captionof{figure}{\CaptionText}}% <--- Why can't I do this?
    \centering
    \includegraphics[width=.25\linewidth]{example-image-a}
    \usebox{\CaptionSavebox}%
    \captionof{figure}{\CaptionText}% <-- don't need this if have the caption in the savebox
    \label{fig: figure label}%
\end{figure}%
\end{document}

1 Answer 1

1

My guess is that since \savebox puts the contents in an \hbox the problem is that the caption can be more than one line. You can fix it by putting it in a \parbox.

There comes an extra empty line below the caption in the box. It seems like it is produced by \caption to ensure it is placed on a line of its own. Below I have removed that line.

\documentclass{article}
\usepackage{lipsum}
\usepackage{caption}
\usepackage{graphicx}

\newsavebox{\CaptionSavebox}
\captionsetup{width=0.20\linewidth}%

\newcommand*{\CaptionText}{This is a caption for the above figure}
\begin{document}
\lipsum[1]

\begin{figure}[htb]
    %\savebox{\CaptionSavebox}{\captionof{figure}{\CaptionText}}% <--- Why can't I do this?
    \centering
    \includegraphics[width=.25\linewidth]{example-image-a}
    %%
    \savebox{\CaptionSavebox}{\parbox[b]{\captionwidth}{\caption{\CaptionText}\vspace{-\baselineskip}}}
    \par
    \usebox{\CaptionSavebox}%
    \rlap{\rule{0.5pt}{\ht\CaptionSavebox} Height=\the\ht\CaptionSavebox Depth=\the\dp\CaptionSavebox}
    %%\captionof{figure}{\CaptionText}% <-- don't need this if have the caption in the savebox
    \label{fig: figure label}%
\end{figure}%

\lipsum[2]
\end{document}

enter image description here

1
  • I think the \vspace{-\baselineskip} that you added is trying to adjust for the \abovecaptionskip and \belowcaptionskip. If you set \abovecaptionskip=0pt and \belowcaptionskip=0pt you can see that you get the correct height without the \vspace{-\baselineskip}. Mar 25, 2018 at 18:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .