SVG with Python

CodeMaven

A number of examples creating SVG images using Python.

More specifically using the svgwrite module.

These scripts all create SVG files that can be embedded in an HTML document usng a simple img tag.

Coordinates are in tuples of (x, y) where (0, 0) is in the top left corner.

Rectangular

examples/python/svg_rectangle.py

import svgwrite

dwg = svgwrite.Drawing(height=200, width=100)
dwg.add( dwg.rect(insert=(200, 100), size=(200, 100), fill='blue', stroke='red', stroke_width=3) )
with open("rect.svg", "w") as fh:
    fh.write(dwg.tostring())


Arrow

examples/python/svg_arrow.py

import svgwrite

dwg = svgwrite.Drawing(height=600, width=600)
hlines = dwg.add(dwg.g(id='hlines', stroke='green'))

hlines.add( dwg.line( start=(20, 20), end=(180, 20), stroke_width=12) )
hlines.add( dwg.line( start=(180, 15), end=(180, 25), stroke_width=2) )
hlines.add( dwg.line( start=(180, 25), end=(190, 20), stroke_width=2) )
hlines.add( dwg.line( start=(180, 15), end=(190, 20), stroke_width=2) )

with open("arrow.svg", "w") as fh:
    fh.write(dwg.tostring())



pip install svgwrite

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Python Maven web site.

Gabor Szabo