Creating SVG files with Python

It’s easy to create SVG files using Python. There’s no need for fancy rendering libraries. Just use a nice XML import/export library such as ElementTree.

This code:

# my favourite XML library
from xml.etree import ElementTree as et

# create an SVG XML element (see the SVG specification for attribute details)
doc = et.Element('svg', width='480', height='360', version='1.1', xmlns='http://www.w3.org/2000/svg')

# add a circle (using the SubElement function)
et.SubElement(doc, 'circle', cx='240', cy='180', r='160', fill='rgb(255, 192, 192)')

# add text (using append function)
text = et.Element('text', x='240', y='180', fill='white', style='font-family:Sans;font-size:48px;text-anchor:middle;dominant-baseline:top')
text.text = 'pink circle'
doc.append(text)

# ElementTree 1.2 doesn't write the SVG file header errata, so do that manually
f = open('sample.svg', 'w')
f.write('\n')
f.write('\n')
f.write(et.tostring(doc))
f.close()

Generates this image (.png file rendered from the output .svg):

Note: I’m using something like this to generate nice diagrams for the next Let’s Make Games report, and figured that it may be of use to others.

Update: Fixed typo in code (missing parentheses).

6 thoughts on “Creating SVG files with Python”

  1. Wow. That is so easy I can’t believe no one else has thanked you for this post yet. Let me be the first, then: THANKS!

  2. Hey that was helpful!! ..thanks šŸ™‚
    What if I want to just view SVG images using python.How do i do that??

  3. This failed for me using Python 3. To get it working I updated the line to be:
    f.write(et.tostring(doc).decode())

    The additional .decode() removes the b’ and ‘ from the result of tostring.

    Thanks for this post, it is still very useful in 2018.

Comments are closed.