从SVG输入生成PDF

Jul*_*ian 26 python pdf django svg

我试图在Django应用程序中使用Python从SVG输入文件生成PDF.

我已经找到了2个工作解决方案:cairo + rsvg和imagemagick但它们都有一个问题:它们有一些奇怪的依赖关系,我不想在服务器上安装,例如DBUS和GTK.

所以我要求另一种从SVG生成PDF的方法,而不必在服务器上安装所有这些愚蠢的依赖项.

ari*_*rie 33

你考虑过svglib吗?

它看起来很有前途,特别是因为reportlab是Django文档中的特色pdf工具.

>>> from svglib.svglib import svg2rlg
>>> from reportlab.graphics import renderPDF
>>>
>>> drawing = svg2rlg("file.svg")
>>> renderPDF.drawToFile(drawing, "file.pdf")
Run Code Online (Sandbox Code Playgroud)

  • 如何将多张图纸添加到一个 PDF 中? (2认同)

sim*_*oes 15

是的,我还建议使用svglibreportlab库来完成这项任务,尽管svglib库的文档很少.我实际上建议你在Django视图中执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)

这样,您永远不需要在服务器上保存临时文件,以便用户无论如何都可以在本地下载.给出的svglib示例需要提供文件的路径...但为什么不提供文件本身?

我已经记录了我在这里使用Django和Raphael SVG库所采取的步骤.

  • 似乎链接已损坏。它会转到默认页面。 (2认同)

fuj*_*471 8

我的回答可能对 macOS 上的人有帮助:

\n\n

我用户CairoSVG

\n\n

首先,安装它:

\n\n
pip install cairosvg\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后你可以在Python中使用它:

\n\n
>>> import cairosvg\n>>> cairosvg.svg2pdf(url=\'image.svg\', write_to=\'image.pdf\')\n
Run Code Online (Sandbox Code Playgroud)\n\n

从它的文档

\n\n
\n

在 macOS 上,\xe2\x80\x99 必须安装 \xc2\xa0 cairo\xc2\xa0 和 \xc2\xa0 libffi\xc2\xa0(以 \xc2\xa0Homebrew\xc2\xa0 为例)

\n
\n