Search code examples
pythonsvg

Parsing SVG file paths with Python


I am working on a robotic project that from an Android running device take a picture then send to cloudconvert.org to convert it into an SVG, then all SVG paths will be translated into x y coordinates and serially send to the robotic arm which will plot them with the pen on or off.

So I've gone so far in this project and the only problem that I am having now is to parse the SVG file into a list of path as a list of string.

I tried minidom but it doesn't seems that it's working. I can actually access the SVG file and but I can't access the path data example 'M 100,200 L 200.300' instead of that I get

>>> from xml.dom import minidom
>>> xmldoc= minidom.parse("C:\Users\DELL\Desktop\drawing-1.svg")
>>> a=xmldoc.getElementsByTagName("svg")[0]
>>> b=a.getElementsByTagName("g")[0]
>>> pth=b.getElementsByTagName("path")[0]
>>> pth
<DOM Element: path at 0x1bb6238>

I just want to access the data inside that dom object as a string and when I tried

>>> print (str(pth))

nothing appears just two blank line then >>> appears again.


Solution

  • I have been working on the same problem my solution was this: 1.convert svg paths to polygons using http://guilhermemussi.com/conversor.html 2. use a relatively simple python script to extract a list of the points. Here is my code it might be sort of messy/inneficient but it gets the job done

    scribble=open("scrib1.txt")
    for line in scribble:
        if line.startswith("<polygon"):
            rightline=line.split('"')
    commas=rightline[13].split(' ') 
    newlist=[]
    for i in commas:
        tup=i.split(',')
        newlist.append((tup[0],tup[1]))