【问题标题】:pdf file generated using reportlab , getting saved as plain text使用reportlab生成的pdf文件,保存为纯文本
【发布时间】:2019-05-11 22:49:02
【问题描述】:

这是我第一次使用reportlab。我从 django 文档中复制了确切的代码。 https://docs.djangoproject.com/en/2.1/howto/outputting-pdf/。当我将文件保存为纯文本文档(文本/纯文本)时,名称保持不变 hello.pdf 并且没有文本。

p = canvas.Canvas(缓冲区) 在这一行中,如果我写文件“hello.pdf”的名称而不是缓冲区并从 fileresponse 方法中删除缓冲区,它可以工作并自动保存为 pdf 文件,但我无法提示用户保存文件并且有两个pdf 中的页面。

def some_view(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)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

我尝试在 django 文档提供的代码中指定 content_type='application/pdf' 但它仍然被保存为纯文本文档。我猜 File 响应无法从 django 文档中提到的 filename 参数猜测文件的类型。

类 FileResponse(open_file, as_attachment=False, filename='', **kwargs) 如果 open_file 没有名称或 open_file 的名称不合适,请使用 filename 参数提供自定义文件名。

添加了 as_attachment 和文件名关键字参数。此外,FileResponse 会设置 Contentheaders(如果它可以猜到)。

如果我使用 2.0 django 文档中的代码,它可以工作。最新的 django 文档 2.1 中是否存在错误?我根据这个官方链接https://bitbucket.org/rptlab/reportlab/src/927995d54048767531a4ad4a0648e46064b0c4c7/README.txt?at=default&fileviewer=file-view-default environment-ubuntu 18.04lts,pycharm,Python 3.5.6,reportlab 3.5.12 安装了所有依赖项。

【问题讨论】:

    标签: python django pdf


    【解决方案1】:

    您需要在返回 FileResponse 之前重置缓冲区位置以开始:

    buffer.seek(io.SEEK_SET)
    

    否则缓冲区将从其末尾开始读取(在画布被写入之后)并返回一个空文件。

    自 v2.1 以来的文档中缺少此问题,应予以修复。

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多