答案1
至少对于一部分文本,您可以将其存储在一个框中并访问该框的几何属性。
为了记住 tex 运行之间的属性并使其在定义框时可用,您可以滥用该totcount
包。
最后但同样重要的一点是,\usepackage{printlen}
这是一种以您喜欢的单位打印值的便捷方法。
下面的例子需要 3 次运行才能收敛。
\documentclass{article}
\usepackage{printlen}
\usepackage{totcount}
\newtotcounter{mywidth}
\newtotcounter{myheight}
\begin{document}
\newsavebox{\mybox}
\savebox{\mybox}{\parbox{\textwidth}{This line is \uselengthunit{mm}\printlength{\totvalue{mywidth}} wide, and has a height of \uselengthunit{mm}\printlength{\totvalue{myheight}} and the line needs to be longer.}}
\usebox{\mybox}
\setcounter{mywidth}{\wd\mybox}
\setcounter{myheight}{\ht\mybox}
\addtocounter{myheight}{\dp\mybox}
\end{document}
答案2
这是一个zref
解决方案,只需要运行两次,但它目前的缺点是盒子名称是固定的。
\documentclass{article}
\usepackage[user]{zref}
\usepackage{xprintlen}
\newsavebox{\mybox}%
\makeatletter
% Define some properties to store
\zref@newprop{width}{\the\wd\mybox}% This is a little bit unfortunate
\zref@newprop{height}{\the\dimexpr\ht\mybox+\dp\mybox}
% Add the properties to the main list
\zref@addprops{main}{width,height}
% Define two expandable properties extraction commands.
\newcommand{\extractwidth}[1]{%
\zref@ifrefundefined{#1}{0pt}{%
\zref@extract{#1}{width}%
}%
}
\newcommand{\extractheight}[1]{%
\zref@ifrefundefined{#1}{0pt}{%
\zref@extract{#1}{height}%
}%
}
\makeatother
\begin{document}
\savebox{\mybox}{\parbox{\textwidth}{This line is \printlen{\extractwidth{boxlabel}} wide, and has a height of \printlen{\extractheight{boxlabel}} and the line needs to be longer.}}\zlabel{boxlabel}
\usebox{\mybox}
\savebox{\mybox}{\rule{10cm}{5cm}}\zlabel{rulelabel}
\usebox{\mybox}
\printlen{\extractwidth{rulelabel}} and \printlen{\extractheight{rulelabel}}
\end{document}