Convert SVG to PDF using Python, rsvg & Cairo

1.4k Views Asked by At

I have managed to read SVG using rsvg and output it to PNG via Cairo, in Python.

Despite there being MANY similar questions, I've not seen any documentation on how to convert SVG into PDF through rsvg & cairo. I am aware of the command-line 'rsvg'/'rsvp-convert' tools, but want to incorporate the functionality into my Python code instead. No launching subprocess either.

For the sake of example, here's basically what I currently use to render PNG:

   img =  cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
   ctx = cairo.Context(img)
   handler= rsvg.Handle(None, svgstr)
   handler.render_cairo(ctx)
   img.write_to_png(pngfilepath)

The question is: how would the code be changed to output PDF instead, so that vector format is kept; rasterization must not happen.

1

There are 1 best solutions below

0
On

Replace your call to cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) with cairo.PDFSurface(filename, width_in_points, height_in_points). I don't know what the default scaling of the PDF surface is, but hopefully you can continue to use the same width and height values as before.

Since you explicitely mention that rasterization must now happen: Cairo "does its best" not to raster things, but there are combinations where cairo has to fall back to rasterized images. You can control the resolution of this images via the set_fallback_resolution method.

Reasons for rasterization include combinations of operations that cannot be expressed in PDF (sorry, I don't know details) and if some rasterized image is drawn to the PDF surface.