Tuesday, April 5, 2011

Shrinking text to the width of other text in latex

This snippet will shrink the text of the first argument to be the width of the second argument. For instance, \shrinktowidthof{AA}{A} will give you two small 'AA's. The if statement means it'll only happen if the first argument is wider than the second, so \shrinktowidthof{a}{A} will just output a normal 'a'. I believe this uses the ifthen, calc, and xstring packages. You also need to do \newlength{\scaleratio} somewhere.

\newcommand{\shrinktowidthof}[2] {
  \setlength{\scaleratio} {
    {1.0pt * \ratio{\widthof{#2}}{\widthof{#1}}}
  }
  \ifthenelse{\lengthtest{\scaleratio < 1.0pt}} {
    \setlength{\scaleratio}{\scaleratio}
    \tokenize{\tokenized}{\the\scaleratio}
    \StrBefore{\tokenized}{pt}[\result]
    \scalebox{\result}{#1}
  } {
    #1
  }
}