Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get svg text size in python

Tags:

python

svg

I am generating SVG image in python (pure, no external libs yet). I want to know what will be a text element size, before I place it properly. Any good idea how to make it? I checked pysvg library but I saw nothing like getTextSize()

like image 801
Jakub M. Avatar asked Nov 04 '22 18:11

Jakub M.


1 Answers

This can be be pretty complicated. To start with, you'll have to familiarize yourself with chapter on text of the SVG specification. Assuming you want to get the width of plain text elements, and not textpath elements, at a minimum you'd have to:

  • Parse the font selection properties, spacing properties and read the xml:space attibute, as well as the writing-mode property (can also be top-bottom instead of just left-to-right and right-to-left).
  • Based on the above, open the correct font, and read the glyph data and extract the widths and heights of the glyphs in your text string. Alone finding the font can be a big task, seeing the multiple places where font files can hide.
  • (optionally) Look through the string for possible ligatures (depending on the language), and replace them with the correct glyph if it exists in the font.
  • Add the widths for all the characters and spaces, the latter depending on the spacing properties and (optionally) possible kerning pairs.

A possible solution would be to use the pango library. You can find python bindings for it in py-gtk. Unfortunately, except from some examples, the documentation for the python bindings is pretty scarce. But it would take care of the details of font loading and determining the extents of a Layout.

Another way is to study the SVG renderer in your browser. But e.g. the support for SVG text in Firefox is limited.

Also instructive is to study how TeX does it, especially the concept (pdf) of boxes (for letters) and glue (for spacing).

like image 165
Roland Smith Avatar answered Nov 15 '22 04:11

Roland Smith