| | 100 | |
|---|
| | 101 | Complex PDFs |
|---|
| | 102 | ============ |
|---|
| | 103 | |
|---|
| | 104 | If you're creating a complex PDF document with ReportLab, consider using the |
|---|
| | 105 | cStringIO_ library as a temporary holding place for your PDF file. The |
|---|
| | 106 | cStringIO library provides a file-like object interface that is particularly |
|---|
| | 107 | efficient. Here's the above "Hello World" example rewritten to use |
|---|
| | 108 | ``cStringIO``:: |
|---|
| | 109 | |
|---|
| | 110 | from cStringIO import StringIO |
|---|
| | 111 | from reportlab.pdfgen import canvas |
|---|
| | 112 | from django.utils.httpwrappers import HttpResponse |
|---|
| | 113 | |
|---|
| | 114 | def some_view(request): |
|---|
| | 115 | # Create the HttpResponse object with the appropriate PDF headers. |
|---|
| | 116 | response = HttpResponse(mimetype='application/pdf') |
|---|
| | 117 | response['Content-Disposition'] = 'attachment; filename=somefilename.pdf' |
|---|
| | 118 | |
|---|
| | 119 | buffer = String() |
|---|
| | 120 | |
|---|
| | 121 | # Create the PDF object, using the StringIO object as its "file." |
|---|
| | 122 | p = canvas.Canvas(buffer) |
|---|
| | 123 | |
|---|
| | 124 | # Draw things on the PDF. Here's where the PDF generation happens. |
|---|
| | 125 | # See the ReportLab documentation for the full list of functionality. |
|---|
| | 126 | p.drawString(100, 100, "Hello world.") |
|---|
| | 127 | |
|---|
| | 128 | # Close the PDF object cleanly. |
|---|
| | 129 | p.showPage() |
|---|
| | 130 | p.save() |
|---|
| | 131 | |
|---|
| | 132 | # Get the value of the StringIO buffer and write it to the response. |
|---|
| | 133 | pdf = buffer.getvalue() |
|---|
| | 134 | buffer.close() |
|---|
| | 135 | response.write(pdf) |
|---|
| | 136 | return response |
|---|
| | 137 | |
|---|
| | 138 | .. cStringIO: http://www.python.org/doc/current/lib/module-cStringIO.html |
|---|
| | 139 | |
|---|
| | 140 | Further resources |
|---|
| | 141 | ================= |
|---|
| | 142 | |
|---|
| | 143 | * PDFlib_ is another PDF-generation library that has Python bindings. To |
|---|
| | 144 | use it with Django, just use the same concepts explained in this article. |
|---|
| | 145 | * HTMLdoc_ is a command-line script that can convert HTML to PDF. It |
|---|
| | 146 | doesn't have a Python interface, but you can escape out to the shell |
|---|
| | 147 | using ``system`` or ``popen`` and retrieve the output in Python. |
|---|
| | 148 | * `forge_fdf in Python`_ is a library that fills in PDF forms. |
|---|
| | 149 | |
|---|
| | 150 | .. _PDFlib: http://www.pdflib.org/ |
|---|
| | 151 | .. _HTMLdoc: http://www.htmldoc.org/ |
|---|
| | 152 | .. _forge_fdf in Python: http://www.accesspdf.com/article.php/20050421092951834 |
|---|