1 from __future__ import absolute_import
2 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
8 from xml.etree import ElementTree
10 def applyTransformString(matrix, transform):
11 while transform != '':
12 if transform[0] == ',':
13 transform = transform[1:].strip()
14 s = transform.find('(')
15 e = transform.find(')')
17 print 'Unknown transform: %s' % (transform)
20 data = map(float, re.split('[ \t,]+', transform[s+1:e].strip()))
21 if tag == 'matrix' and len(data) == 6:
22 matrix = numpy.matrix([[data[0],data[1],0],[data[2],data[3],0],[data[4],data[5],1]], numpy.float64) * matrix
23 elif tag == 'translate' and len(data) == 1:
24 matrix = numpy.matrix([[1,0,data[0]],[0,1,0],[0,0,1]], numpy.float64) * matrix
25 elif tag == 'translate' and len(data) == 2:
26 matrix = numpy.matrix([[1,0,0],[0,1,0],[data[0],data[1],1]], numpy.float64) * matrix
27 elif tag == 'scale' and len(data) == 1:
28 matrix = numpy.matrix([[data[0],0,0],[0,data[0],0],[0,0,1]], numpy.float64) * matrix
29 elif tag == 'scale' and len(data) == 2:
30 matrix = numpy.matrix([[data[0],0,0],[0,data[1],0],[0,0,1]], numpy.float64) * matrix
31 elif tag == 'rotate' and len(data) == 1:
32 r = math.radians(data[0])
33 matrix = numpy.matrix([[math.cos(r),math.sin(r),0],[-math.sin(r),math.cos(r),0],[0,0,1]], numpy.float64) * matrix
34 elif tag == 'rotate' and len(data) == 3:
35 matrix = numpy.matrix([[1,0,0],[0,1,0],[data[1],data[2],1]], numpy.float64) * matrix
36 r = math.radians(data[0])
37 matrix = numpy.matrix([[math.cos(r),math.sin(r),0],[-math.sin(r),math.cos(r),0],[0,0,1]], numpy.float64) * matrix
38 matrix = numpy.matrix([[1,0,0],[0,1,0],[-data[1],-data[2],1]], numpy.float64) * matrix
39 elif tag == 'skewX' and len(data) == 1:
40 matrix = numpy.matrix([[1,0,0],[math.tan(data[0]),1,0],[0,0,1]], numpy.float64) * matrix
41 elif tag == 'skewY' and len(data) == 1:
42 matrix = numpy.matrix([[1,math.tan(data[0]),0],[0,1,0],[0,0,1]], numpy.float64) * matrix
44 print 'Unknown transform: %s' % (transform)
46 transform = transform[e+1:].strip()
50 f = re.search('^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?', f).group(0)
58 def __init__(self, x, y, matrix):
60 self._relMatrix = numpy.matrix([[matrix[0,0],matrix[0,1]], [matrix[1,0],matrix[1,1]]])
61 self._startPoint = complex(x, y)
64 def addLineTo(self, x, y):
65 self._points.append({'type': Path.LINE, 'p': complex(x, y)})
67 def addArcTo(self, x, y, rot, rx, ry, large, sweep):
72 'radius': complex(rx, ry),
77 def addCurveTo(self, x, y, cp1x, cp1y, cp2x, cp2y):
81 'cp1': complex(cp1x, cp1y),
82 'cp2': complex(cp2x, cp2y)
86 self._points.append({'type': Path.LINE, 'p': self._startPoint})
88 def getPoints(self, accuracy = 1):
89 pointList = [self._m(self._startPoint)]
91 for p in self._points:
92 if p['type'] == Path.LINE:
94 pointList.append(self._m(p1))
95 elif p['type'] == Path.ARC:
97 rot = math.radians(p['rot'])
100 #http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
102 p1alt = diff #TODO: apply rot
103 p2alt = -diff #TODO: apply rot
106 x1alt2 = p1alt.real*p1alt.real
107 y1alt2 = p1alt.imag*p1alt.imag
109 f = x1alt2 / rx2 + y1alt2 / ry2
111 r *= math.sqrt(f+0.000001)
115 f = math.sqrt((rx2*ry2 - rx2*y1alt2 - ry2*x1alt2) / (rx2*y1alt2+ry2*x1alt2))
116 if p['large'] == p['sweep']:
118 cAlt = f * complex(r.real*p1alt.imag/r.imag, -r.imag*p1alt.real/r.real)
120 c = cAlt + (p1 + p2) / 2 #TODO: apply rot
122 a1 = math.atan2((p1alt.imag - cAlt.imag) / r.imag, (p1alt.real - cAlt.real) / r.real)
123 a2 = math.atan2((p2alt.imag - cAlt.imag) / r.imag, (p2alt.real - cAlt.real) / r.real)
125 large = abs(a2 - a1) > math.pi
126 if large != p['large']:
132 pCenter = self._m(c + complex(math.cos(a1 + 0.5*(a2-a1)) * r.real, math.sin(a1 + 0.5*(a2-a1)) * r.imag))
133 dist = abs(pCenter - self._m(p1)) + abs(pCenter - self._m(p2))
134 segments = int(dist / accuracy) + 1
135 for n in xrange(1, segments):
136 pointList.append(self._m(c + complex(math.cos(a1 + n*(a2-a1)/segments) * r.real, math.sin(a1 + n*(a2-a1)/segments) * r.imag)))
138 pointList.append(self._m(p2))
140 elif p['type'] == Path.CURVE:
143 cp1 = self._m(p['cp1'])
144 cp2 = self._m(p['cp2'])
146 pCenter = p1_*0.5*0.5*0.5 + cp1*3.0*0.5*0.5*0.5 + cp2*3.0*0.5*0.5*0.5 + p2*0.5*0.5*0.5
147 dist = abs(pCenter - p1_) + abs(pCenter - p2)
148 segments = int(dist / accuracy) + 1
149 for n in xrange(1, segments):
150 f = n / float(segments)
152 point = p1_*g*g*g + cp1*3.0*g*g*f + cp2*3.0*g*f*f + p2*f*f*f
153 pointList.append(point)
160 def getSVGPath(self):
161 p0 = self._m(self._startPoint)
162 ret = 'M %f %f ' % (p0.real, p0.imag)
163 for p in self._points:
164 if p['type'] == Path.LINE:
166 ret += 'L %f %f' % (p0.real, p0.imag)
167 elif p['type'] == Path.ARC:
170 ret += 'A %f %f 0 %d %d %f %f' % (radius.real, radius.imag, 1 if p['large'] else 0, 1 if p['sweep'] else 0, p0.real, p0.imag)
171 elif p['type'] == Path.CURVE:
173 cp1 = self._m(p['cp1'])
174 cp2 = self._m(p['cp2'])
175 ret += 'C %f %f %f %f %f %f' % (cp1.real, cp1.imag, cp2.real, cp2.imag, p0.real, p0.imag)
180 tmp = numpy.matrix([p.real, p.imag, 1], numpy.float64) * self._matrix
181 return complex(tmp[0,0], tmp[0,1])
183 tmp = numpy.matrix([p.real, p.imag], numpy.float64) * self._relMatrix
184 return complex(tmp[0,0], tmp[0,1])
187 def __init__(self, filename):
189 self.tagProcess['rect'] = self._processRectTag
190 self.tagProcess['line'] = self._processLineTag
191 self.tagProcess['polyline'] = self._processPolylineTag
192 self.tagProcess['polygon'] = self._processPolygonTag
193 self.tagProcess['elipse'] = self._processPolygonTag
194 self.tagProcess['circle'] = self._processCircleTag
195 self.tagProcess['ellipse'] = self._processEllipseTag
196 self.tagProcess['path'] = self._processPathTag
197 self.tagProcess['use'] = self._processUseTag
198 self.tagProcess['g'] = self._processGTag
199 self.tagProcess['a'] = self._processGTag
200 self.tagProcess['svg'] = self._processGTag
201 self.tagProcess['text'] = None #No text implementation yet
202 self.tagProcess['image'] = None
203 self.tagProcess['metadata'] = None
204 self.tagProcess['defs'] = None
205 self.tagProcess['style'] = None
206 self.tagProcess['marker'] = None
207 self.tagProcess['desc'] = None
208 self.tagProcess['filter'] = None
209 self.tagProcess['linearGradient'] = None
210 self.tagProcess['radialGradient'] = None
211 self.tagProcess['pattern'] = None
212 self.tagProcess['title'] = None
213 self.tagProcess['animate'] = None
214 self.tagProcess['animateColor'] = None
215 self.tagProcess['animateTransform'] = None
216 self.tagProcess['set'] = None
217 self.tagProcess['script'] = None
220 self.tagProcess['namedview'] = None
222 self.tagProcess['SVGTestCase'] = None
225 f = open(filename, "r")
226 self._xml = ElementTree.parse(f)
227 self._recursiveCount = 0
228 self._processGTag(self._xml.getroot(), numpy.matrix(numpy.identity(3, numpy.float64)))
232 def _processGTag(self, tag, baseMatrix):
234 if e.get('transform') is None:
237 matrix = applyTransformString(baseMatrix, e.get('transform'))
238 tagName = e.tag[e.tag.find('}')+1:]
239 if not tagName in self.tagProcess:
240 print 'unknown tag: %s' % (tagName)
241 elif self.tagProcess[tagName] is not None:
242 self.tagProcess[tagName](e, matrix)
244 def _processUseTag(self, tag, baseMatrix):
245 if self._recursiveCount > 16:
247 self._recursiveCount += 1
248 id = tag.get('{http://www.w3.org/1999/xlink}href')
250 for e in self._xml.findall(".//*[@id='%s']" % (id[1:])):
251 if e.get('transform') is None:
254 matrix = applyTransformString(baseMatrix, e.get('transform'))
255 tagName = e.tag[e.tag.find('}')+1:]
256 if not tagName in self.tagProcess:
257 print 'unknown tag: %s' % (tagName)
258 elif self.tagProcess[tagName] is not None:
259 self.tagProcess[tagName](e, matrix)
260 self._recursiveCount -= 1
262 def _processLineTag(self, tag, matrix):
263 x1 = toFloat(tag.get('x1', '0'))
264 y1 = toFloat(tag.get('y1', '0'))
265 x2 = toFloat(tag.get('x2', '0'))
266 y2 = toFloat(tag.get('y2', '0'))
267 p = Path(x1, y1, matrix)
271 def _processPolylineTag(self, tag, matrix):
272 values = map(toFloat, re.split('[, \t]+', tag.get('points', '').strip()))
273 p = Path(values[0], values[1], matrix)
274 for n in xrange(2, len(values)-1, 2):
275 p.addLineTo(values[n], values[n+1])
278 def _processPolygonTag(self, tag, matrix):
279 values = map(toFloat, re.split('[, \t]+', tag.get('points', '').strip()))
280 p = Path(values[0], values[1], matrix)
281 for n in xrange(2, len(values)-1, 2):
282 p.addLineTo(values[n], values[n+1])
286 def _processCircleTag(self, tag, matrix):
287 cx = toFloat(tag.get('cx', '0'))
288 cy = toFloat(tag.get('cy', '0'))
289 r = toFloat(tag.get('r', '0'))
290 p = Path(cx-r, cy, matrix)
291 p.addArcTo(cx+r, cy, 0, r, r, False, False)
292 p.addArcTo(cx-r, cy, 0, r, r, False, False)
295 def _processEllipseTag(self, tag, matrix):
296 cx = toFloat(tag.get('cx', '0'))
297 cy = toFloat(tag.get('cy', '0'))
298 rx = toFloat(tag.get('rx', '0'))
299 ry = toFloat(tag.get('rx', '0'))
300 p = Path(cx-rx, cy, matrix)
301 p.addArcTo(cx+rx, cy, 0, rx, ry, False, False)
302 p.addArcTo(cx-rx, cy, 0, rx, ry, False, False)
305 def _processRectTag(self, tag, matrix):
306 x = toFloat(tag.get('x', '0'))
307 y = toFloat(tag.get('y', '0'))
308 width = toFloat(tag.get('width', '0'))
309 height = toFloat(tag.get('height', '0'))
310 if width <= 0 or height <= 0:
314 if rx is not None or ry is not None:
329 if rx > 0 and ry > 0:
330 p = Path(x+rx, y, matrix)
331 p.addLineTo(x+width-rx, y)
332 p.addArcTo(x+width,y+ry, 0, rx, ry, False, True)
333 p.addLineTo(x+width, y+height-ry)
334 p.addArcTo(x+width-rx,y+height, 0, rx, ry, False, True)
335 p.addLineTo(x+rx, y+height)
336 p.addArcTo(x,y+height-ry, 0, rx, ry, False, True)
338 p.addArcTo(x+rx,y, 0, rx, ry, False, True)
341 p = Path(x, y, matrix)
342 p.addLineTo(x,y+height)
343 p.addLineTo(x+width,y+height)
344 p.addLineTo(x+width,y)
348 def _processPathTag(self, tag, matrix):
349 pathString = tag.get('d', '').replace(',', ' ')
355 for command in re.findall('[a-df-zA-DF-Z][^a-df-zA-DF-Z]*', pathString):
356 params = re.split(' +', command[1:].strip())
357 if len(params) > 0 and params[0] == '':
359 if len(params) > 0 and params[-1] == '':
361 params = map(toFloat, params)
367 path = Path(x, y, matrix)
368 self.paths.append(path)
370 while len(params) > 1:
379 path = Path(x, y, matrix)
380 self.paths.append(path)
382 while len(params) > 1:
389 while len(params) > 1:
396 while len(params) > 1:
419 while len(params) > 6:
422 path.addArcTo(x, y, params[2], params[0], params[1], params[3] > 0, params[4] > 0)
426 while len(params) > 6:
429 path.addArcTo(x, y, params[2], params[0], params[1], params[3] > 0, params[4] > 0)
433 while len(params) > 5:
440 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
443 while len(params) > 5:
450 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
453 while len(params) > 3:
460 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
463 while len(params) > 3:
470 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
473 while len(params) > 3:
480 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
483 while len(params) > 3:
490 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
493 while len(params) > 1:
500 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
503 while len(params) > 1:
510 path.addCurveTo(x, y, c1x, c1y, c2x, c2y)
512 elif command == 'z' or command == 'Z':
514 x = path._startPoint.real
515 y = path._startPoint.imag
517 print 'Unknown path command:', command, params
520 if __name__ == '__main__':
521 for n in xrange(1, len(sys.argv)):
522 print 'File: %s' % (sys.argv[n])
523 svg = SVG(sys.argv[n])
525 f = open("test_export.html", "w")
527 f.write("<!DOCTYPE html><html><body>\n")
528 f.write("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style='width:%dpx;height:%dpx'>\n" % (1000, 1000))
529 f.write("<g fill-rule='evenodd' style=\"fill: gray; stroke:black;stroke-width:2\">\n")
530 f.write("<path d=\"")
531 for path in svg.paths:
532 points = path.getPoints()
533 f.write("M %f %f " % (points[0].real, points[0].imag))
534 for point in points[1:]:
535 f.write("L %f %f " % (point.real, point.imag))
539 f.write("<g style=\"fill: none; stroke:red;stroke-width:1\">\n")
540 f.write("<path d=\"")
541 for path in svg.paths:
542 f.write(path.getSVGPath())
547 f.write("</body></html>")