I am using python library svgwrite to generate svg file. I have to put two lines of text exactly at the center of a rectangle. The texts should be left aligned. The width and height of the rectangle is known. I inserted two text lines inside a group container, and aligned them by setting their 'text_anchor' attribute to 'start', and x position to 0. Here is the code:
svg = svgwrite.Drawing(size=(210*mm, 297*mm), viewBox=('0 0 210 297'))
rect_width = 80
rect_height = 25
rect = svg.rect(insert=(0, 0), size=(rect_width, rect_height), fill='none', stroke='red', stroke_width=1)
font_size = 6 #in mm
style = "font-family:Arial; font-size:%i" % (font_size)
text_1 = svg.text('Line 1', insert=(0,0), style=style, text_anchor='start', dominant_baseline='hanging')
text_2 = svg.text('Longer Line 2', insert=(0, font_size), style=style, text_anchor='start', dominant_baseline='hanging')
text_group = svg.g()
text_group.add(text_1)
text_group.add(text_2)
x_pos = rect_width/2
y_pos = rect_height/2-font_size
text_group.translate(x_pos, y_pos)
svg.add(rect)
svg.add(text_group)
The output is shown here: See generated SVG
It seems the vertical position of 'text_group' is OK (at the center). But Horizontal position should be more to the left. This is achievable if I can get the width of 'text_group', and modify 'x_pos':
x_pos = rect_width/2 - text_group_width/2
I couldn't find any way to get the width of the text group in svgwrite. Is there any method to get the width, or if there is any alternative solution to this problem?
I found this
svg.text(style="text-anchor:middle")
to be useful for centrally aligning text