How do I convert an svg
to png
, in Python? I am storing the svg
in an instance of StringIO
. Should I use the pyCairo library? How do I write that code?
Advertisement
Answer
The answer is “pyrsvg” – a Python binding for librsvg.
There is an Ubuntu python-rsvg package providing it. Searching Google for its name is poor because its source code seems to be contained inside the “gnome-python-desktop” Gnome project GIT repository.
I made a minimalist “hello world” that renders SVG to a cairo surface and writes it to disk:
JavaScript
x
15
15
1
import cairo
2
import rsvg
3
4
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)
5
6
ctx = cairo.Context(img)
7
8
## handle = rsvg.Handle(<svg filename>)
9
# or, for in memory SVG data:
10
handle= rsvg.Handle(None, str(<svg data>))
11
12
handle.render_cairo(ctx)
13
14
img.write_to_png("svg.png")
15
Update: as of 2014 the needed package for Fedora Linux distribution is: gnome-python2-rsvg
. The above snippet listing still works as-is.