Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created June 24, 2019 09:58
Show Gist options
  • Select an option

  • Save lovasoa/7c040ae6c620ae8b1b51d5e8abd141ac to your computer and use it in GitHub Desktop.

Select an option

Save lovasoa/7c040ae6c620ae8b1b51d5e8abd141ac to your computer and use it in GitHub Desktop.
import xml.sax
import sys
import json
class InkscapeSvgHandler(xml.sax.ContentHandler):
def __init__(self):
self.o = {}
self.t = 1554660678511
def startElement(self, name, attrs):
if name not in ("path","line","rect"):
return
self.t += 1
o = {
"color": attrs.get("stroke", "#000000"),
"size": float(attrs.get("stroke-width", 1)),
"opacity": float(attrs.get("opacity", 1)),
"id": attrs.get("id"),
"time": self.t,
"_children": [],
}
if name == "path":
o["type"] = "line"
o["tool"] = "Pencil"
if "d" in attrs:
d = attrs["d"]
pts = [float(x) for x in d.split() if not x.isalpha()]
for x,y in zip(pts[::2], pts[1::2]):
o["_children"].append({
"x": x,
"y": y,
"parent": o["id"],
"type": "child",
"tool": "Pencil",
})
elif name=="line":
o["type"] = "straight"
o["tool"] = "Straight line"
o["x"] = float(attrs.get("x1"))
o["y"] = float(attrs.get("y1"))
o["x2"] = float(attrs.get("x2"))
o["y2"] = float(attrs.get("y2"))
elif name=="rect":
o["type"] = "rect"
o["tool"] = "Rectangle"
o["x"] = float(attrs.get("x"))
o["y"] = float(attrs.get("y"))
o["x2"] = float(attrs.get("width")) + o["x"]
o["y2"] = float(attrs.get("height")) + o["y"]
self.o[o["id"]] = o
parser = xml.sax.make_parser()
handler = InkscapeSvgHandler()
parser.setContentHandler(handler)
parser.parse(sys.stdin)
json.dump(handler.o, sys.stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment