svg.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import struct
  2. import lxml.etree as etree
  3. from io import BytesIO
  4. from transform.svg import stripStyles, affinityDesignerCompensate, viewboxCompensate
  5. from transform.bytes import outputTableBytes
  6. class SVGDoc:
  7. """
  8. Class representing an SVG document in an SVG table.
  9. """
  10. def __init__(self, glyphID, glyph):
  11. self.img = glyph.imgDict['svg']
  12. self.ID = glyphID
  13. def toTTX(self):
  14. # create the structure that encapsulates the SVG image
  15. svgDoc = etree.Element("svgDoc", {"startGlyphID": str(self.ID), "endGlyphID" : str(self.ID) })
  16. # Add a glyph ID to the SVG.
  17. svgRoot = self.img.data.getroot()
  18. svgRoot.attrib["id"] = f"glyph{self.ID}"
  19. newSVGTree = svgRoot.getroottree()
  20. finishedSVG = newSVGTree
  21. cdata = etree.CDATA(etree.tostring(finishedSVG, method="xml", pretty_print=False, xml_declaration=True, encoding="UTF-8"))
  22. svgDoc.text = cdata
  23. return svgDoc
  24. class SVG:
  25. """
  26. Class representing an SVG table.
  27. """
  28. def __init__(self, m, glyphs):
  29. self.version = 0 # hardcoded; the only version.
  30. self.SVGDocumentList = []
  31. self.reserved = 0 # reserved; set to 0.
  32. for ID, g in enumerate(glyphs["img_empty"]): # it has to be img_empty because we need those glyph indexes.
  33. if g.imgDict:
  34. self.SVGDocumentList.append(SVGDoc(ID, g))
  35. def toTTX(self):
  36. svgTable = etree.Element("SVG")
  37. # - TTX doesnt have version for SVG table.
  38. for svgDoc in self.SVGDocumentList:
  39. svgTable.append(svgDoc.toTTX())
  40. return svgTable
  41. def toBytes(self):
  42. # TODO: compile and attach SVGDocumentList.
  43. # - compile and calculate Offset32 to SVGDocumentList here
  44. svg = struct.pack( ">HI"
  45. , self.version # UInt16
  46. # - offsetToSVGDocumentList # Offset32/UInt32
  47. , self.reserved # UInt32
  48. )
  49. return outputTableBytes(svg) # placeholder
  50. # Attach SVGDocumentList afterwards.