Outputting PDFs with Django
The advantage of generating PDF files dynamically is that you can createcustomized PDFs for different purposes — say, for different users or differentpieces of content.
For example, Django was used at kusports.com to generate customized,printer-friendly NCAA tournament brackets, as PDF files, for peopleparticipating in a March Madness contest.
The ReportLab library is . A user guide (notcoincidentally, a PDF file) is also available for download.You can install ReportLab with :
If that command doesn't raise any errors, the installation worked.
The key to generating PDFs dynamically with Django is that the ReportLab APIacts on file-like objects, and Django's objects accept file-like objects.
Here's a "Hello World" example:
- The response will automatically set the MIME type _application/pdf_based on the filename extension. This tells browsers that the document is aPDF file, rather than an HTML file or a generic _application/octet-stream_binary content.
- When
as_attachment=True
is passed toFileResponse
, it sets theappropriate header and that tells Web browsers topop-up a dialog box prompting/confirming how to handle the document even if adefault is set on the machine. If theas_attachment
parameter is omitted,browsers will handle the PDF using whatever program/plugin they've beenconfigured to use for PDFs. - Hooking into the ReportLab API is easy: The same buffer passed as the firstargument to
canvas.Canvas
can be fed to the class. - Note that all subsequent PDF-generation methods are called on the PDFobject (in this case,
p
) — not onbuffer
.
注解
ReportLab is not thread-safe. Some of our users have reported odd issueswith building PDF-generating Django views that are accessed by many peopleat the same time.
Notice that there isn't a lot in these examples that's PDF-specific — just thebits using reportlab
. You can use a similar technique to generate anyarbitrary format that you can find a Python library for. Also see for another example and some techniques you can usewhen generated text-based formats.
Django Packages provides a comparison of packages that help generate PDF filesfrom Django.