Sim*_*mon 6 python django canvas reportlab httpresponse
在ReportLab中,可以将Drawing对象写入不同的渲染器,例如
d = shapes.Drawing(400, 400)
renderPDF.drawToFile(d, 'test.pdf')
Run Code Online (Sandbox Code Playgroud)
在Django中,Canvas对象可以通过httpresponse发送,例如:
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'filename=test.pdf'
c = canvas.Canvas(response)
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我的问题是我有一个使用Drawing对象的reportLab脚本,它保存到本地文件系统.我现在把它放在Django视图中,并想知道是否有办法不保存到本地文件系统,而是发送回客户端.
我希望我能清楚地描述这个问题.
谢谢你的建议!
更新
事实证明renderPDF中有一个函数:
renderPDF.draw(drawing, canvas, x, y)
Run Code Online (Sandbox Code Playgroud)
它可以在给定的画布中渲染drawing()对象.
在Django中使用ReportLab而不保存到磁盘实际上非常简单.DjangoDocs中甚至有一些例子(https://docs.djangoproject.com/en/dev/howto/outputting-pdf)
这个技巧基本归结为使用"像对象一样的文件"而不是实际的文件.大多数人都使用StringIO.
你可以很简单地做到这一点
from cStringIO import StringIO
def some_view(request):
filename = 'test.pdf'
# Make your response and prep to attach
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % (filename)
tmp = StringIO()
# Create a canvas to write on
p = canvas.Canvas(tmp)
# With someone on
p.drawString(100, 100, "Hello world")
# Close the PDF object cleanly.
p.showPage()
p.save()
# Get the data out and close the buffer cleanly
pdf = tmp.getvalue()
tmp.close()
# Get StringIO's body and write it out to the response.
response.write(pdf)
return response
Run Code Online (Sandbox Code Playgroud)