pythoncairolibrsvg

How to resize svg image file using librsvg Python binding


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.


Solution

  • 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: