代码之家  ›  专栏  ›  技术社区  ›  Nigel

django PDF FileResponse“未能加载PDF文档。”

  •  0
  • Nigel  · 技术社区  · 6 年前

    我试图从django视图生成和输出PDF。我效仿了 django documentation using ReportLab 但下载的PDF并没有在任何PDF阅读器中打开。

    我使用Python3.7.0,Django==2.1.3,reportlab==3.5.12。我试着加上 content_type="application/pdf" 到“FileResponse”,但仍然有相同的问题。

    import io
    from django.http import FileResponse
    from reportlab.pdfgen import canvas
    
    def printPDF(request):
        # Create a file-like buffer to receive PDF data.
        buffer = io.BytesIO()
    
        # Create the PDF object, using the buffer as its "file."
        p = canvas.Canvas(buffer)
    
    
        p.drawString(100, 100, "Hello world.")
    
    
        p.showPage()
        p.save()
    
        return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
    

    生成的PDF应该在所有PDF阅读器中打开。但我得到的是“未能加载PDF文档”

    2 回复  |  直到 6 年前
        1
  •  3
  •   santicalcagno    6 年前

    似乎有点可疑 BytesIO FileResponse . 下面的对我有用。

    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
    
        2
  •  1
  •   cuto    6 年前

    buffer = BytesIO() 用于存储pdf文档,而不是文件。在将其与FileResponse一起返回之前,您需要将流位置重置为其开始位置:

    buffer.seek(io.SEEK_SET)
    

    现在pdf下载应该可以按预期工作了。