Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get display width of a string from Linux command line?

I am working on an AWK script that processes a text file line by line, formats them and stuffs them into an SVG file text field. The SVG takes care of text wrapping automatically, but I want to predict where each line will wrap. (I need some characters to repeat and extend close to the end of the line). I know the exact font, font size, and width of the text field.

Is there a standard utility in Linux or easily available in Ubuntu that will give a width in pixels or inches given a string, font, and font size?

For example:

get-width 'Nimbus Sans L' 18 "test string"
returns "x pixels"
like image 810
kcghost Avatar asked Sep 16 '25 08:09

kcghost


1 Answers

You can do this with the ghostscript interpreter, assuming you have that and the fonts are set up correctly.

Here is the possibly mysterious incantation:

gs -dQUIET -sDEVICE=nullpage 2>/dev/null - \
   <<<'18 /NimbusSanL-Regu   findfont exch scalefont setfont
      (test string)          stringwidth pop =='

Using -dQUIET suppresses warnings about font substitution, which is probably not a good idea until you have some idea about how to name the fonts you're looking for.

ghostscript is not a layout engine, and you may find the measurement doesn't work with complicated bidirectional text, combining characters, or East Asian languages. (I tested it with a little Arabic, and it was OK, but no guarantees.) It does not kern, so it will normally produce measurements a little larger than a good layout engine, and possibly a lot larger if the font positions diacritics using kerning.

Finally, if your text includes unbalanced parentheses or backslashes, you'll need to escape them. I use the following:

"$(sed 's/[()\\]/\\&/g' <<<"$text")"

That's because Postscript strings are enclosed in (...) -- (test string) -- and are allowed to include balanced parentheses. Unbalanced parentheses will usually generate a syntax error, unless they are backslash-escaped.

like image 175
rici Avatar answered Sep 18 '25 00:09

rici