Access height of a \parbox

The following solution patches \@iiiparbox to get the height in the second parameter. The value is stored in the dimension register \parboxheight.

If the height is not set, LaTeX uses \relax for this parameter. Then, \parboxheight is set to zero. If you want to know, whether the height parameter was set the optional argument, an additional switch can be used.

Example:

\documentclass{article}

\newdimen\parboxheight

\makeatletter
\newcommand*{\org@iiiparbox}{}
\let\org@iiiparbox\@iiiparbox
\renewcommand*{\@iiiparbox}[2]{%
  \ifx\relax#2%
    \setlength{\parboxheight}{0pt}%
  \else
    \setlength{\parboxheight}{#2}%
  \fi
  \org@iiiparbox{#1}{#2}%
}
\makeatother

\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\fbox{\parbox{100pt}{Some text, some more text, and \the\linewidth}}

\fbox{%
  \parbox[][80pt][t]{100pt}{%
    \raggedright
    Some text, some more text, and width \the\linewidth, %
    and the height \the\parboxheight.%
  }%
}
\end{document}

Result

With switch:

\documentclass{article}

\newif\ifparboxheight
\newdimen\parboxheight

\makeatletter
\newcommand*{\org@iiiparbox}{}
\let\org@iiiparbox\@iiiparbox
\renewcommand*{\@iiiparbox}[2]{%
  \ifx\relax#2%
    \parboxheightfalse
    \setlength{\parboxheight}{0pt}%
  \else
    \parboxheighttrue
    \setlength{\parboxheight}{#2}%
  \fi
  \org@iiiparbox{#1}{#2}%
}
\makeatother


\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\newcommand*{\TestText}{%
  \raggedright
  Some text, some more text. The width is \the\linewidth
  \ifparboxheight
    \ and the height is \the\parboxheight
  \fi
  .%
}

\fbox{\parbox{100pt}{\TestText}}

\fbox{\parbox[][80pt][t]{100pt}{\TestText}}

\end{document}

Result with switch


The dimension is in argument #2 to \@iiiparbox, so we can patch \parbox in order to save the argument in a length register.

\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\newlength{\parboxtodim}
\patchcmd{\@iiiparbox}
  {\hsize}
  {\ifx\relax#2\else\setlength{\parboxtodim}{#2}\fi\hsize}
  {}{}
\makeatother

\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\fbox{\parbox{100pt}{Some text, some more text, and \the\linewidth}}

% here I'd like something like \parboxheight or similar
\fbox{\parbox[][200pt][t]{100pt}{%
  Some text, some more text, and \the\linewidth, and \the\parboxtodim
}}

\end{document}

enter image description here


\documentclass{standalone}
\newbox\mybox
\savebox\mybox{\parbox{100pt}{This is a test.}}
\begin{document}
\the\ht\mybox\ and \the\wd\mybox
\end{document}

enter image description here