[Django]-Django PDF FileResponse "Failed to load PDF document."

5👍

buffer = BytesIO() is used instead of a file to store the pdf document. Before returning it with FileResponse you need to reset the stream position to its start:

buffer.seek(io.SEEK_SET)

Now the pdf download should work as expected.

3👍

There seems to be something fishy going on with the interaction of BytesIO and FileResponse. The following worked for me.

def printPDF(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=hello.pdf'
    p = canvas.Canvas(response)
    p.drawString(100, 100, "Hello world.")
    p.showPage()
    p.save()
    return response

Leave a comment