All formats

drawsvg

LanguagePython 3
LicenseMIT
Repositorygithub.com/cduck/drawsvg
DocumentationREADME, API reference
Depends onnothing for SVG output; CairoSVG for PNG, imageio for GIF/MP4
Read / writeno / yes (SVG, HTML; PNG, GIF and MP4 with extras)

drawsvg builds an SVG document from Python objects: Drawing, Rectangle, Circle, Path, Text, Group, gradients, markers, clip paths and more. SVG attributes are keyword arguments, with _ turned into - (stroke_width=2 becomes stroke-width="2"). It can add SMIL keyframe animations, save frame-by-frame animations as GIF or MP4, and display drawings inline in Jupyter notebooks.

Version 2 uses the SVG coordinate system (y down) and snake_case names; code written for drawSvg 1.x needs updating. It doesn’t read existing SVG files.

Installation#

Shell
pip install "drawsvg~=2.0"
# with PNG, GIF and MP4 output (needs the Cairo C library)
pip install "drawsvg[all]~=2.0"

Basic usage: create an SVG file#

Python
import drawsvg as draw

d = draw.Drawing(200, 100)  # width, height; origin is the top-left corner

d.append(draw.Rectangle(10, 10, 80, 80, rx=8, fill="#4a90e2"))
d.append(draw.Circle(150, 50, 40, fill="orange", stroke="black", stroke_width=2))
d.append(draw.Text("Hello", 16, 50, 55, text_anchor="middle", fill="white"))  # text, font size, x, y

d.save_svg("out.svg")

How to draw a path#

Path has methods named after the SVG path commands, and they can be chained:

Python
p = draw.Path(stroke="black", stroke_width=2, fill="none")
p.M(10, 90).L(60, 40).C(80, 20, 120, 20, 140, 40).Z()
d.append(p)

How to use gradients and groups#

Python
grad = draw.LinearGradient(0, 0, 200, 0)  # x1, y1, x2, y2
grad.add_stop(0, "red")
grad.add_stop(1, "blue")
d.append(draw.Rectangle(0, 0, 200, 10, fill=grad))

g = draw.Group(id="axes", transform="translate(0 100)", stroke="gray")
g.append(draw.Line(0, 0, 200, 0))
g.append(draw.Line(0, 0, 0, -100))
d.append(g)

The gradient is added to <defs> automatically when it’s used.

How to save a PNG#

Python
d.set_pixel_scale(2)    # 2 output pixels per SVG unit
d.save_png("out.png")   # needs drawsvg[raster] / cairosvg

How to get the SVG as a string#

Python
svg_text = d.as_svg()

In Jupyter, a Drawing as the last expression of a cell displays inline; d.rasterize() shows it as PNG.

Tips#