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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With