Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to convert an SVG file to PDF in python using the svglib and reportlab packages. Here is the SVG file.
XML
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="blue" />
</svg>

Here is the code I am using to convert (got this from svglib webpage).

>>> from svglib.svglib import svg2rlg
>>> from reportlab.graphics import renderPDF
>>> drawing = svg2rlg("file.svg")
>>> renderPDF.drawToFile(drawing, "file.pdf")

The code runs fine without any error or exception but the file.pdf thus generated is a blank file. I mean that when I open this PDF file I see nothing but only white background page with nothing on it.

Where am I going wrong ?
Posted

I have just worked on something similar and used this thread as a starting point.

However, I stumbled upon a problem, that may be of interest for others as well:

When one actually has defined the svg dimensions in the svg file by using physical units, like inches or mm, the renderPDF.drawToFile method will interprete all those units as Points.

So if you want to do the conversion printer ready, meaning there will be no scaling needed during printing of the PDF, you can do it like this:

from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF
drawing = svg2rlg("file.svg")
scaleFactor = 1./0.3527
drawing.width *= scaleFactor
drawing.height *= scaleFactor
drawing.scale(scaleFactor, scaleFactor)
renderPDF.drawToFile(drawing, "file.pdf")


The scale factor above is from mm to Points. Just look up the factor you need, e.g. here:
http://en.wikipedia.org/wiki/Point_%28typography%29#Current_DTP_point_system[^]
 
Share this answer
 
Need to make that last line:
renderPDF.drawToFile(drawing, "file.pdf", autoSize=0)

The normal parameter value for autoSize is 1 which results in the PDF being the same size as the drawing.

The problem is with svg file having no size parameters. You can e.g. change the svg opening tag to:
XML
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="1000px" width="1000px">


to get a similar (visible) result without using autoSize=0
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900