rendering a ReportLab pdf built from SimpleDocTemplate

前端 未结 2 678
面向向阳花
面向向阳花 2021-02-08 02:43

I\'ve a got a django app that currently generates pdfs using a canvas that the user can download. I create a StringIO buffer, do some stuff and then send call response.write.

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-08 02:57

    For people who are working with python3 and django 1.7+ some changes to the answer need to be done.

    from django.shortcuts import HttpResponse
    import io
    from reportlab.platypus import SimpleDocTemplate, BaseDocTemplate
    
    def view(request):
        buffer = io.BytesIO()
    
        doc = # ... create your SimpleDocTemplate / BaseDocTemplate
        # create the usual story
        story = []
        # ...
        doc.build(story)
    
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=your_name.pdf'
        response.write(buffer.getvalue())
        buffer.close()
    
        return response
    

提交回复
热议问题