diff --git a/tests/draw/svg/test_text.py b/tests/draw/svg/test_text.py
index 491a2968c..40c328354 100644
--- a/tests/draw/svg/test_text.py
+++ b/tests/draw/svg/test_text.py
@@ -343,6 +343,27 @@ def test_text_anchor_end_tspan(assert_pixels):
''')
+@assert_no_logs
+def test_text_anchor_middle_end_tspan(assert_pixels):
+ assert_pixels('''
+ _______BBBBBB_______
+ _______BBBBBB_______
+ ____________BBBBBB__
+ ____________BBBBBB__
+ ''', '''
+
+
+ ''')
+
+
@assert_no_logs
def test_text_rotate(assert_pixels):
assert_pixels('''
diff --git a/weasyprint/svg/__init__.py b/weasyprint/svg/__init__.py
index f29eb89ad..7dfd6e9d3 100644
--- a/weasyprint/svg/__init__.py
+++ b/weasyprint/svg/__init__.py
@@ -445,12 +445,7 @@ def draw_node(self, node, font_size, fill_stroke=True):
self.stream.transform(*(old_ctm @ new_ctm.invert).values)
# Handle text anchor
- if node.tag == 'text':
- text_anchor = node.get('text-anchor')
- children = tuple(node)
- if children and not node.text:
- text_anchor = children[0].get('text-anchor')
- if node.tag == 'text' and text_anchor in ('middle', 'end'):
+ if (text_anchor := node.get('text-anchor')) in ('middle', 'end'):
group = self.stream.add_group(0, 0, 0, 0) # BBox set after drawing
original_streams.append(self.stream)
self.stream = group
@@ -472,7 +467,12 @@ def draw_node(self, node, font_size, fill_stroke=True):
# Draw node children
if node.display and node.tag not in DEF_TYPES:
for child in node:
+ if text_anchor in ('middle', 'end'):
+ new_stream = self.stream
+ self.stream = original_streams[-1]
self.draw_node(child, font_size, fill_stroke)
+ if text_anchor in ('middle', 'end'):
+ self.stream = new_stream
visible_text_child = (
TAGS.get(node.tag) == text and
TAGS.get(child.tag) == text and
@@ -491,7 +491,7 @@ def draw_node(self, node, font_size, fill_stroke=True):
self.tree.set_svg_size(svg, concrete_width, concrete_height)
# Handle text anchor
- if node.tag == 'text' and text_anchor in ('middle', 'end'):
+ if text_anchor in ('middle', 'end'):
group_id = self.stream.id
self.stream = original_streams.pop()
self.stream.push_state()