Skip to content

Commit

Permalink
Correctly handle multiple tspans with text-anchor set
Browse files Browse the repository at this point in the history
Fix #2353.
  • Loading branch information
liZe committed Jan 20, 2025
1 parent 9d14920 commit 513397e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
21 changes: 21 additions & 0 deletions tests/draw/svg/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
''', '''
<style>
@page { size: 20px 4px }
svg { display: block }
</style>
<svg width="20px" height="4px" xmlns="http://www.w3.org/2000/svg">
<text x="10" y="10" font-family="weasyprint" font-size="2" fill="blue">
<tspan x="10" y="1.5" text-anchor="middle">ABC</tspan>
<tspan x="18" y="3.5" text-anchor="end">ABC</tspan>
</text>
</svg>
''')


@assert_no_logs
def test_text_rotate(assert_pixels):
assert_pixels('''
Expand Down
14 changes: 7 additions & 7 deletions weasyprint/svg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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()
Expand Down

0 comments on commit 513397e

Please sign in to comment.