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:

  1. Request an SVG loader from GTK/GDK
  2. Set the desired image size
  3. Load the image
  4. 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 )

Tags: ,
| March 26th, 2007 | Posted in blog |

One Response to “Rendering an SVG to a GTK image”

  1. Jairus Says:

    Thanks, worked great!

Leave a Reply