I have written a simple function to calculate the width of a line of text and display it using tikz
:
\documentclass{article}
%\usepackage{mathpazo}
\usepackage{domitian}
\usepackage[T1]{fontenc}
%\let\oldstylenums\oldstyle
\usepackage{tikz}
\usepackage{tkz-euclide}
\usetikzlibrary{math}
\usetikzlibrary{calc}
\usetikzlibrary{fpu}
\usetikzlibrary{fit}
\ExplSyntaxOn
\box_new:N \l_my_otherbox
\dim_new:N \l_my_dim
\dim_new:N \l_my_htdim
\dim_new:N \l_my_dpdim
\NewDocumentCommand{\boxlen}{m}
{
\hbox_set:Nn \l_my_otherbox {#1}
\dim_set:Nn \l_my_dim {\box_wd:N \l_my_otherbox}
\dim_set:Nn \l_my_htdim {\box_ht:N \l_my_otherbox}
\dim_set:Nn \l_my_dpdim {\box_dp:N \l_my_otherbox}
\begin{tikzpicture}
\node[draw,text~width=9cm,align=left,fill=white,draw=black,inner~sep=0pt] (box) at (0,0)
{#1};
\draw[line~width=2pt]~($(box.south~west)+(0,-.5cm)$)~--~+(9cm,0) node[below,pos=0.5] {9 cm};
\draw[red,line~width=2pt]~let~\p1=(box.west),\p2=(box.base)~in~($(box.base)+(\x1-\x2,-\dim_use:N \l_my_dpdim)$)~--~+(\dim_use:N \l_my_dim,0) node[below,pos=0.5]
{\fp_eval:n {round(\dim_to_decimal_in_cm:n {\dim_use:N \l_my_dim},2)}cm};
\end{tikzpicture}
}
\ExplSyntaxOff
\begin{document}
This part of the document uses the \verb+domitian+ font family:\par
\boxlen{Long word.}
\vskip 2ex
\boxlen{\textbf{Even longer} word.}
\vskip 2ex
\boxlen{\textbf{Emphasize a word} or do not emphasize a word.}
\vskip 2ex
\boxlen{Emphasize a word or do not emphasize a word.}
{ % use computer modern roman
\fontfamily{cmr}\selectfont
This part of the document uses the \verb+Computer Modern Roman+ font family:\par
\boxlen{Long word.}
\vskip 2ex
\boxlen{\textbf{Even longer} word.}
\vskip 2ex
\boxlen{\textbf{Emphasize a word} or do not emphasize a word.}
\vskip 2ex
\boxlen{Emphasize a word or do not emphasize a word.}
}
\end{document}
The function works fine when I use Computer Modern Roman (by the way it is really difficult to get the codes for the \fontfamily
command). But if I use domitian
, as the sentence gets longer the width calculated by \box_wd
seems to be smaller than the actual length of the text.
It seems that \box_wd
is written for specific font families so I wonder if there is a way to calculate an adjustment for non-standard font families.
\wd
) is the size of the text in that font. the box commands themselves do not select any font.\dim_set_eq:NN
is wrong and errors.text badly ragged
one gets the expected result tex.stackexchange.com/a/132748/2388