properly rewrite svg viewPort using minidom for xml

This avoids raising the 'Not enough space for size' exception.
This commit is contained in:
Stefan Grosshauser 2019-06-03 23:16:04 +02:00 committed by Florian Festi
parent c3aac6f5eb
commit 443c8a1c38
1 changed files with 11 additions and 17 deletions

View File

@ -71,13 +71,12 @@ class SVGFile(object):
p.ParseFile(open(self.filename, "rb")) p.ParseFile(open(self.filename, "rb"))
def rewriteViewPort(self): def rewriteViewPort(self):
f = open(self.filename, "r+") """
s = f.read(1024) Modify SVG file to have the correct width, height and viewPort attributes.
"""
m = re.search(r"""<svg[^>]*(width="(\d+pt)" height="(\d+pt)" viewBox="0 (0 (\d+) (\d+))") version="1.1">""", s) from xml.dom.minidom import parse, parseString
# parse the XML file
# minx = 10*int(self.minx//10)-10 svg_dom = parse(self.filename)
# as we don't rewrite the left border keep it as 0
self.minx = self.minx or 0 self.minx = self.minx or 0
self.miny = self.miny or 0 self.miny = self.miny or 0
@ -93,17 +92,12 @@ class SVGFile(object):
miny = 10 * int(self.miny // 10) - 10 miny = 10 * int(self.miny // 10) - 10
maxy = 10 * int(self.maxy // 10) + 10 maxy = 10 * int(self.maxy // 10) + 10
if m: svg_dom.documentElement.attributes['width'].nodeValue = "%imm" % (maxx-minx)
f.seek(m.start(1)) svg_dom.documentElement.attributes['height'].nodeValue = "%imm" % (maxy-miny)
s = ('width="%imm" height="%imm" viewBox="%i %i %i %i"' % svg_dom.documentElement.attributes['viewBox'].nodeValue = "%i %i %i %i" % (minx, miny, maxx - minx, maxy - miny)
(maxx - minx, maxy - miny, minx, miny, maxx - minx, maxy - miny))
if len(s) > len(m.group(1)): f = open(self.filename, "w")
raise ValueError("Not enough space for size") svg_dom.writexml(f)
f.write(s + " " * (len(m.group(1)) - len(s)))
else:
raise ValueError("Could not understand SVG file")
unit2mm = {"mm" : 1.0, unit2mm = {"mm" : 1.0,
"cm" : 10.0, "cm" : 10.0,