我想在Django應用程序中使用Python從SVG輸入文件生成PDF。從SVG輸入生成PDF
我已經找到2個工作解決方案:cairo + rsvg和imagemagick,但他們都有一個問題:他們有一些奇怪的依賴關係,我不想在服務器上安裝,例如DBUS和GTK。
所以我要求另一種從SVG生成PDF的方法,而不必在服務器上安裝所有這些愚蠢的依賴關係。
我想在Django應用程序中使用Python從SVG輸入文件生成PDF。從SVG輸入生成PDF
我已經找到2個工作解決方案:cairo + rsvg和imagemagick,但他們都有一個問題:他們有一些奇怪的依賴關係,我不想在服務器上安裝,例如DBUS和GTK。
所以我要求另一種從SVG生成PDF的方法,而不必在服務器上安裝所有這些愚蠢的依賴關係。
您考慮過svglib嗎?
它看起來很有希望,特別是當reportlab是Django文檔中的featured pdf tool。
>>> from svglib.svglib import svg2rlg
>>> from reportlab.graphics import renderPDF
>>>
>>> drawing = svg2rlg("file.svg")
>>> renderPDF.drawToFile(drawing, "file.pdf")
是的,我也建議使用svglib和reportlab library該任務雖然是SVGALib之上庫的很少文檔。我真的建議做在你的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
這樣,你永遠需要保存在服務器上的臨時文件,爲用戶只是本地下載反正。給出的svglib示例需要提供文件的路徑......但爲什麼不只是提供文件本身呢?
我已經記錄了我使用Django和Raphael SVG庫here所採取的步驟。
您需要爲版本0.6.3添加「導入字符串」才能使用python 2.7。
你可以使用我的Frok,直到pypy更新。
pip install git+git://github.com/ddehghan/libsvg.git
這完全是我的問題,但我有另一個限制:與Unicode兼容(對於svg內的非英文文本)。 – saeedgnu 2011-05-09 09:02:14