在 ReportLab 中,Drawing 对象可以写入不同的渲染器,例如
d = shapes.Drawing(400, 400)
renderPDF.drawToFile(d, 'test.pdf')
在 Django 中,Canvas 对象可以通过 httpresponse 发送,例如:
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'filename=test.pdf'
c = canvas.Canvas(response)
在我的例子中,我的问题是我有一个使用绘图对象的 reportLab 脚本,该脚本保存到本地文件系统。我现在把它放在 Django View 中,想知道是否有办法不保存到本地文件系统而是发送回客户端。
我希望我把这个问题描述清楚。
感谢您的任何建议!
更新
原来在renderPDF中有一个函数:
renderPDF.draw(drawing, canvas, x, y)
它可以在给定的 Canvas 中渲染 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
关于python - Django 报告实验室 : using Drawing object to create PDF and return via Httpresponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9847533/