编写你的视图¶

FileResponse

下面是一个“你好世界”的例子:

import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

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.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

代码和注释应该是不言自明的,但有几点值得一提:

as_attachment=TrueFileResponseContent-Dispositionas_attachmentfilenamecanvas.CanvasFileResponsepbuffershowPage()save()

备注

ReportLab不是线程安全的。我们的一些用户报告了构建生成django视图的PDF时出现的一些奇怪问题,这些视图可同时被许多人访问。