Generating PDFs from SVG input

2019-01-21 11:26发布

I am trying to generate a PDF from a SVG input file with Python in a Django application.

I have already found 2 working solutions: cairo+rsvg and imagemagick but they both have one problem: They have some strange dependencies that I do not want to install on a server, for example DBUS and GTK.

So I am asking for another method for generating a PDF from SVG without having to install all these stupid dependencies on a server.

3条回答
女痞
2楼-- · 2019-01-21 11:58

Have you considered svglib?

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

>>> from svglib.svglib import svg2rlg
>>> from reportlab.graphics import renderPDF
>>>
>>> drawing = svg2rlg("file.svg")
>>> renderPDF.drawToFile(drawing, "file.pdf")
查看更多
Rolldiameter
3楼-- · 2019-01-21 12:00

You will need to add "import string" for version 0.6.3 to work with python 2.7.

you can use my frok until the pypy is updated.

pip install git+git://github.com/ddehghan/libsvg.git
查看更多
Emotional °昔
4楼-- · 2019-01-21 12:08

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 SvgRenderer
from reportlab.graphics import renderPDF
import xml.dom.minidom
@csrf_exempt
def 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.

查看更多
登录 后发表回答