How to resize svg image file using librsvg Python binding

When rasterizing an svg file, I would like to be able to set the width and height for the resulting png file. In the following code, only the canvas is set to the required width and height, the actual image content with the original svg file size is displayed in the upper left corner of the canvas (500, 600).

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 content of the image the same with the canvas? I tried

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

but got

 TypeError: property 'width' is not writable 

Also, documents for linking python librsvg seem extremely rare, only some random snippets of code on the cairo website.

+4
source share
2 answers

Librsvg has a resize function , but it is deprecated.

Set up in Cairo to resize the picture:

  • customize the scale transformation matrix in your cairo context.
  • draw an SVG using the .render_cairo () method
  • write your surface in PNG
+6
source

This is the code that works for me. It implements the answer from Luper above:

 import rsvg import cairo # Load the svg data svg_xml = open('topthree.svg', 'r') svg = rsvg.Handle() svg.write(svg_xml.read()) svg.close() # Prepare the Cairo context img = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) ctx = cairo.Context(img) # Scale whatever is written into this context # in this case 2x both x and y directions ctx.scale(2, 2) svg.render_cairo(ctx) # Write out into a PNG file png_io = StringIO.StringIO() img.write_to_png(png_io) with open('sample.png', 'wb') as fout: fout.write(png_io.getvalue()) 
+2
source

All Articles