Forgot password?
 Create new account
View 92|Reply 0

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

[Copy link]

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

hbghlyj Posted at 2023-3-10 23:03:56 |Read mode
  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")
Copy the Code
Example CTQPMR\bulletBADO 变为 CTQPMR\bulletBADO 可见位置未改变

手机版Mobile version|Leisure Math Forum

2025-4-20 22:06 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list