Django ReportLab: using Drawing object to create PDF and return via Httpresponse

不问归期 提交于 2019-12-12 08:49:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!