views:

721

answers:

1

When rasterizing svg file, I would like to be able to set width and height for the resulting png file. With the following code, only the canvas is set to the desired width and height, the actual image content with the original svg file dimension is rendered in the top left corner on the (500, 600) canvas.

import cairo
import rsvg

WIDTH, HEIGHT  = 500, 600
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)

ctx = cairo.Context(surface)

svg = rsvg.Handle(file="test.svg")
svg.render_cairo(ctx)

surface.write_to_png("test.png")

What should I do to make the image content same size with cairo canvas? I tried

svg.set_property('width', 500)
svg.set_property('height', 500)

but got

TypeError: property 'width' is not writable

Also documents for librsvg python binding seem to be extremely rare, only some random code snippets on cairo site.

+3  A: 

There is a resize function in librsvg, but it is deprecated.

Set up a scale matrix in Cairo to change the size of your drawing:

  • setup a scale transformation matrix on your cairo context
  • draw your SVG with the .render_cairo() method
  • write your surface to PNG
Luper Rouch
Will rescaling the already rasterized image result in data loss of the original vector image?
btw0
The cairo transformation matrix operates on vector data drawed after setting it. You don't scale the rasterized image but the commands issued by librsvg that produce it.
Luper Rouch
Good to know, thank you.
btw0