找回密码
 快速注册
搜索
查看: 29|回复: 0

[Python]SVG 将嵌套的<tspan>改为独立的<text>

[复制链接]

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

hbghlyj 发表于 2023-3-10 23:03 |阅读模式


  1. import xml.etree.ElementTree as ET
  2. tree = ET.parse("input.svg")
  3. root = tree.getroot()
  4. SVG_NS = "http://www.w3.org/2000/svg"
  5. ET.register_namespace("", SVG_NS)
  6. prefix = "{" + SVG_NS + "}"
  7. # iterate over all text elements
  8. for text in root.findall(prefix+"text"):
  9. if len(text) == 0:
  10. continue
  11. # iterate over all tspan child elements
  12. for tspan in text:
  13. # create a new text element with same attributes as tspan
  14. new_text = ET.Element(prefix+"text",tspan.attrib)
  15. # set the translate attribute to the new text element
  16. new_text.set('transform', text.get('transform'))
  17. # append the children of tspan to the new text element
  18. new_text.text=tspan[0].text
  19. # replace the tspan element with the new text element
  20. root.append(new_text)
  21. root.remove(text)
  22. for text in root.findall(prefix+"text"):
  23. x = float(text.get('x') or 0)
  24. y = float(text.get('y') or 0)
  25. transform = text.get('transform').replace(","," ")
  26. if transform is not None and 'translate' in transform:
  27. transform=transform[10:-1]
  28. dx,dy=transform.split(" ")
  29. x += float(dx)
  30. y += float(dy)
  31. text.set('x',str(x))
  32. text.set('y',str(y))
  33. text.attrib.pop('transform')
  34. tree.write("converted/output.svg")
复制代码
Example CTQPMR\bulletBADO 变为 CTQPMR\bulletBADO 可见位置未改变

手机版|悠闲数学娱乐论坛(第3版)

GMT+8, 2025-3-4 15:19

Powered by Discuz!

× 快速回复 返回顶部 返回列表