Using python, how can I predict the pixel width of text in SVG?

I use python to generate an SVG with text that can change, and I would like to place a translucent rectangle behind it to guarantee some contrast when it overlays another graphic element later.

Unfortunately, I don't know how to predict the pixel extents of a particular line of text in SVG. I can choose which font I use (but I don’t think that a mono error will be acceptable) and what font size I use.

How can I use python to predict the extents of SVG text so that I can create a rectangle of the appropriate size?

+4
source share
1 answer

, , Python. , FreeType . .

- SVG- .

:

<svg width="360" height="100" viewBox="0 0 360 100">
  <defs>
    <filter x="0" y="0" width="1" height="1" id="text-bg">
      <feFlood flood-color="#ff0" flood-opacity="0.5" />
      <feComposite in="SourceGraphic" />
    </filter>
  </defs>
  <rect x="0" y="0" width="400" height="100" fill="#444" stroke="none" />
  <path d="m0 10 40 80 40-80 40 80 40-80 40 80 40-80 40 80 40-80 40 80"
        stroke="#888" stroke-width="10" fill="none" />
  <text font-family="Arial" font-weight="bold" filter="url(#text-bg)"
        x="180" y="50" font-size="20" fill="#000" text-anchor="middle">
    Edit this text and reload the SVG
  </text>
</svg>
Hide result
+4

Source: https://habr.com/ru/post/1627598/


All Articles