生成PDF文件

2018-03-05  本文已影响195人  大爷的二舅

Django能够使用视图动态地输出PDF文件。 这是由优秀的开源ReportLab Python PDF库实现的。 动态生成PDF文件的优点是您可以为不同的目的创建自定义的PDF - 例如,针对不同的用户或不同的内容片段。

安装Reportlab

ReportLab库在PyPI上可用。 用户指南(并非巧合的是PDF文件)也可以下载。 您可以使用pip安装ReportLab:

$ pip install reportlab 

通过将它导入Python交互式解释器来测试您的安装:

>>> import reportlab 

如果该命令不会引发任何错误,则安装成功了,可以正常工作。

写入你的视图

使用Django动态生成PDF的关键是ReportLab API,就像csv库一样,可以处理文件类对象,如Django的HttpResponse。 这是一个Hello World示例:

from reportlab.pdfgen import canvas
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;    
      filename="somefilename.pdf"'

    # Create the PDF object, using the response object as its "file."
    p = canvas.Canvas(response)

    # 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()
    return response 

代码和评论应该是不言自明的,但有几件事情值得一提:

  response['Content-Disposition'] = 'filename="somefilename.pdf"'
复杂的PDF文件

如果您使用ReportLab创建复杂的PDF文档,请考虑将io库用作PDF文件的临时保存位置。 这个库提供了一个特别高效的文件类对象接口。 以上是重写为使用io的Hello World示例:

from io import BytesIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;   
      filename="somefilename.pdf"'

    buffer = BytesIO()

    # Create the PDF object, using the BytesIO object 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.
    p.showPage()
    p.save()

    # Get the value of the BytesIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response 
更多资源
其他可能性

有很多其他类型的内容可以用Python生成。 这里有一些更多的想法和一些指向你可以用来实现它们的库的指针:

一般来说,任何能够写入文件的Python库都可以挂钩到Django中。 可能性是巨大的。 现在我们已经介绍了生成非HTML内容的基础知识,让我们加强抽象层次。 Django附带一些非常漂亮的内置工具,用于生成一些常见类型的非HTML内容。

上一篇 下一篇

猜你喜欢

热点阅读