Generating PDFs from SVG input Generating PDFs from SVG input python python

Generating PDFs from SVG input


Have you considered svglib?

It looks quite promising, especially as reportlab is the featured pdf tool in Django's docs.

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


Yes, I would also suggest using svglib and the reportlab library for this task although there is very little documentation of the svglib library. I would actually suggest doing the following in your Django view:

from svglib.svglib import SvgRendererfrom reportlab.graphics import renderPDFimport xml.dom.minidom@csrf_exemptdef export_svg(request):    # Get data from client side via POST variables    svg = request.POST.get("svg")    doc = xml.dom.minidom.parseString(svg.encode( "utf-8" ))    svg = doc.documentElement    # Create new instance of SvgRenderer class    svgRenderer = SvgRenderer()    svgRenderer.render(svg)    drawing = svgRenderer.finish()    # Instead of outputting to a file, we simple return    # the data and let the user download to their machine    pdf = renderPDF.drawToString(drawing)    response = HttpResponse(mimetype='application/pdf')    response.write(pdf)         # If one were to remove the 'attachment; ' from this line    # it would simple invoke the browsers default PDF plugin    response["Content-Disposition"]= "attachment; filename=converted.pdf"    return response

This way you never need to save a temporary file on the server for the user to just download locally anyway. The svglib example that is given requires providing a path to a file... but why not just provide the file itself?

I have documented the steps I have taken using Django and the Raphael SVG library here.


My answer may help someone on macOS:

I user CairoSVG

Firstly, install it with:

pip install cairosvg

Then you can use it in Python:

>>> import cairosvg>>> cairosvg.svg2pdf(url='image.svg', write_to='image.pdf')

from its documentation:

on macOS, you’ll have to install cairo and libffi (with Homebrew for example)