Home:ALL Converter>Autofill SVG object with text (Python / svgwrite)?

Autofill SVG object with text (Python / svgwrite)?

Ask Time:2019-10-18T00:45:58         Author:Zubo

Json Formatter

I am creating an SVG using svgwrite in Python and would like to create some object, say, a rectangle with sizes xsize and ysize, and also some text to fill it:

import svgwrite 
xsize = 20 
ysize = 30
xcoord = 0 
ycoord = 0 
mystr = 'some text more text'
myfontsize = '20px'
dwg = svgwrite.Drawing(filename='mysvg.svg', debug=True)
dwg.add(dwg.rect((xcoord, ycoord), (xsize, ysize), fill='red'))
dwg.add(dwg.text(mystr, insert=(xcoord, ycoord), font_size=myfontsize, fill='black'))
dwg.save()

I'd like to automatically adjust myfontsize or use some better way to make 'mystr' always fit the box, i.e. fit to xsize.

The only way I came up with is using a monospace font and dividing xsize by len(mystr).

Is there a better solution?

Author:Zubo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/58437324/autofill-svg-object-with-text-python-svgwrite
yy