Django ReportLab: Using a Drawing Object to Create a PDF and Return Through Httpresponse

In ReportLab, a Drawing object can be written to different renderers, for example

d = shapes.Drawing(400, 400)
renderPDF.drawToFile(d, 'test.pdf')

and in Django, a Canvas object can be sent via httpresponse, for example:

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 the Drawing object, which is saved on the local file system. Now I put it in Django views and wonder if there is a way not to save on the local file system, but instead send it back to the client.

I hope I will clearly describe this issue.

Thanks for any advice!

Updates

It turns out that renderPDF has a function:

renderPDF.draw(drawing, canvas, x, y)

which can display the drawing () object in this canvas.

+5
3

, renderPDF :

renderPDF.draw(, , x, y) drawing() .

+2

ReportLab Django . 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 body and write it out to the response.
    response.write(pdf)
    return response
+6

asString , , "png", "gif" "jpg".

renderPDF.drawToFile(d, 'test.pdf')

binaryStuff = d.asString('gif')
return HttpResponse(binaryStuff, 'image/gif')

.

https://code.djangoproject.com/wiki/Charts .

0
source

All Articles