Rendering an SVG to a GTK image
Once upon a time loading SVG in python was done via pycairo and libsvg-cairo:
import cairo
import cairo.svg
svg = cairo.svg.Context()
svg.parse( 'filename.svg' )
...
Since then, libsvg-cairo has been deprecated (http://cairographics.org/PycairoFAQ). Nowadays, librsvg provides an SVG loader for GTK, so that it is possible to simply do
import gtk
i = gtk.Image()
i.set_from_file( 'x.svg' )
...
But I needed a finer control over the generation of image – in particular, I wanted to be able to zoom in to and out of the vector graphics image, much like rsvg-view. If you follow the example above and first render the image, then start scaling it, you will not get a high-resolution scaled vector image, but a scaled low-resolution rendering of the vector image.
After reading the rsvg-view sources, I figured out that what I wanted could be accomplished by:
- Request an SVG loader from GTK/GDK
- Set the desired image size
- Load the image
- Set the image to the resulting pixbuf
The following code does the magic:
# svg_data - a string containing the contents of the SVG file
# image - an instance of gtk.Image
# w, h - desired image resolution
loader = gtk.gdk.PixbufLoader( 'svg' )
loader.set_size( w, h )
loader.write( svg_data )
loader.close()
pb = loader.get_pixbuf()
image.set_from_pixbuf( pb )
| Posted in blog | 1 Comment »