Embed .SVG files into PDF using reportlab


Question

I have written a script in python that produces matplotlib graphs and puts them into a pdf report using reportlab.

I am having difficulty embedding SVG image files into my PDF file. I've had no trouble using PNG images but I want to use SVG format as this produces better quality images in the PDF report.

This is the error message I am getting:

IOError: cannot identify image file

Does anyone have suggestions or have you overcome this issue before?

1
5
5/13/2013 11:42:54 AM

Accepted Answer

You need to make sure you are importing PIL (Python Imaging Library) in your code so that ReportLab can use it to handle image types like SVG. Otherwise it can only support a few basic image formats.

That said, I recall having some trouble, even when using PIL, with vector graphics. I don't know if I tried SVG but I remember having a lot of trouble with EPS.

0
5/13/2013 12:59:18 PM

Yesterday I succeeded in using svglib to add a SVG Image as a reportlab Flowable.

so this drawing is an instance of reportlab Drawing, see here:

from reportlab.graphics.shapes import Drawing

a reportlab Drawing inherits Flowable:

from reportlab.platypus import Flowable

Here is a minimal example that also shows how you can scale it correctly (you must only specify path and factor):

from svglib.svglib import svg2rlg
drawing = svg2rlg(path)
sx = sy = factor
drawing.width, drawing.height = drawing.minWidth() * sx, drawing.height * sy
drawing.scale(sx, sy)
#if you want to see the box around the image
drawing._showBoundary = True

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon