Search code examples
pythonsvgcad

Setting default units in svg (Python svgwrite)


I'm generating SVG drawings using python's svgwrite. Every time I want to draw something, I find myself doing this ugly awkward thing:

line = drawing.line(start = "%dmm" % start, end = "%dmm" % end)

I wish I could just do:

line = drawing.line(start = start, end = end)

Is there a way to set the default units to 'mm' for the entire svg drawing?


Solution

  • A possible way is to set the viewBox attribute along with the document sizing,

    dwg = svgwrite.Drawing('myDrawing.svg', size=('170mm', '130mm'), viewBox=('0 0 170 130'))
    
    dwg.add(dwg.line(start=(30, 30), end=(50,50)))
    
    dwg.save()
    

    produces for me,

    <?xml version="1.0" encoding="utf-8" ?>
    
    <svg baseProfile="full" height="130mm" version="1.1" viewBox="0 0 170 130" width="170mm"
    xmlns="http://www.w3.org/2000/svg" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xlink="http://www.w3.org/1999/xlink"><defs /><line x1="30" x2="50" y1="30" y2="50" />     </svg>