问题
In ReportLab, Drawing object can be written into different renderers, e.g
d = shapes.Drawing(400, 400)
renderPDF.drawToFile(d, 'test.pdf')
and in Django, Canvas object can be sent via httpresponse, e.g.:
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'filename=test.pdf'
c = canvas.Canvas(response)
in my case, my problem is that I have a reportLab script using Drawing object which saves to local file system. I now put it in Django views, and wondering whether there is a way to not save to local file system but instead sent back to client.
I hope I describe this question clearly.
Thanks for any advice!
updates
it turns out there is a function in renderPDF:
renderPDF.draw(drawing, canvas, x, y)
which can render drawing() object in the given canvas.
回答1:
Using ReportLab in Django without saving to disk is actually pretty easy. There are even examples in the DjangoDocs (https://docs.djangoproject.com/en/dev/howto/outputting-pdf)
The trick basically boils down to using a "file like object" instead of an actual file. Most people use StringIO for this.
You could do it pretty simply with
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
回答2:
it turns out there is a function in renderPDF:
renderPDF.draw(drawing, canvas, x, y) which can render drawing() object in the given canvas.
回答3:
Drawing has a method called asString with a one required attribute that represents the required drawing format such as 'png', 'gif' or 'jpg'. so instead of calling
renderPDF.drawToFile(d, 'test.pdf')
You could call
binaryStuff = d.asString('gif')
return HttpResponse(binaryStuff, 'image/gif')
Without the need to save your drawing to the disc.
Check https://code.djangoproject.com/wiki/Charts for full example.
来源:https://stackoverflow.com/questions/9847533/django-reportlab-using-drawing-object-to-create-pdf-and-return-via-httpresponse