Debian Codegraph @

docs/howto/outputting-pdf.txt

raw
1 =======================
2 How to create PDF files
3 =======================
4
5 This document explains how to output PDF files dynamically using Django views.
6 This is made possible by the excellent, open-source ReportLab_ Python PDF
7 library.
8
9 The advantage of generating PDF files dynamically is that you can create
10 customized PDFs for different purposes -- say, for different users or different
11 pieces of content.
12
13 For example, Django was used at kusports.com_ to generate customized,
14 printer-friendly NCAA tournament brackets, as PDF files, for people
15 participating in a March Madness contest.
16
17 .. _ReportLab: https://docs.reportlab.com/
18 .. _kusports.com: https://www2.kusports.com/
19
20 Install ReportLab
21 =================
22
23 The ReportLab library is :pypi:`available on PyPI <reportlab>`. A `user guide`_
24 (not coincidentally, a PDF file) is also available for download.
25 You can install ReportLab with ``pip``:
26
27 .. console::
28
29 $ python -m pip install reportlab
30
31 Test your installation by importing it in the Python interactive interpreter:
32
33 .. code-block:: pycon
34
35 >>> import reportlab
36
37 If that command doesn't raise any errors, the installation worked.
38
39 .. _user guide: https://www.reportlab.com/docs/reportlab-userguide.pdf
40
41 Write your view
42 ===============
43
44 The key to generating PDFs dynamically with Django is that the ReportLab API
45 acts on file-like objects, and Django's :class:`~django.http.FileResponse`
46 objects accept file-like objects.
47
48 Here's a "Hello World" example::
49
50 import io
51 from django.http import FileResponse
52 from reportlab.pdfgen import canvas
53
54
55 def some_view(request):
56 # Create a file-like buffer to receive PDF data.
57 buffer = io.BytesIO()
58
59 # Create the PDF object, using the buffer as its "file."
60 p = canvas.Canvas(buffer)
61
62 # Draw things on the PDF. Here's where the PDF generation happens.
63 # See the ReportLab documentation for the full list of functionality.
64 p.drawString(100, 100, "Hello world.")
65
66 # Close the PDF object cleanly, and we're done.
67 p.showPage()
68 p.save()
69
70 # FileResponse sets the Content-Disposition header so that browsers
71 # present the option to save the file.
72 buffer.seek(0)
73 return FileResponse(buffer, as_attachment=True, filename="hello.pdf")
74
75 The code and comments should be self-explanatory, but a few things deserve a
76 mention:
77
78 * The response will automatically set the MIME type :mimetype:`application/pdf`
79 based on the filename extension. This tells browsers that the document is a
80 PDF file, rather than an HTML file or a generic
81 :mimetype:`application/octet-stream` binary content.
82
83 * When ``as_attachment=True`` is passed to ``FileResponse``, it sets the
84 appropriate ``Content-Disposition`` header and that tells web browsers to
85 pop-up a dialog box prompting/confirming how to handle the document even if a
86 default is set on the machine. If the ``as_attachment`` parameter is omitted,
87 browsers will handle the PDF using whatever program/plugin they've been
88 configured to use for PDFs.
89
90 * You can provide an arbitrary ``filename`` parameter. It'll be used by browsers
91 in the "Save as..." dialog.
92
93 * You can hook into the ReportLab API: The same buffer passed as the first
94 argument to ``canvas.Canvas`` can be fed to the
95 :class:`~django.http.FileResponse` class.
96
97 * Note that all subsequent PDF-generation methods are called on the PDF
98 object (in this case, ``p``) -- not on ``buffer``.
99
100 * Finally, it's important to call ``showPage()`` and ``save()`` on the PDF
101 file.
102
103 .. note::
104
105 ReportLab is not thread-safe. Some of our users have reported odd issues
106 with building PDF-generating Django views that are accessed by many people
107 at the same time.
108
109 Other formats
110 =============
111
112 Notice that there isn't a lot in these examples that's PDF-specific -- just the
113 bits using ``reportlab``. You can use a similar technique to generate any
114 arbitrary format that you can find a Python library for. Also see
115 :doc:`/howto/outputting-csv` for another example and some techniques you can use
116 when generated text-based formats.
117
118 .. seealso::
119
120 Django Packages provides a `comparison of packages
121 <https://djangopackages.org/grids/g/pdf/>`_ that help generate PDF files
122 from Django.