I’ve been involved in a number of project where I need to create pdf reports from a set of data using the Django framework. The easiest way for me to do this is generate the pdf directly from html.
I will provide a list of software required, and how to program a django view to generate the pdf.
Here’s the software you’ll need:
pisa: http://pypi.python.org/pypi/pisa/
ReportLab: http://www.reportlab.org/downloads.html
html5lib: http://code.google.com/p/html5lib/downloads/list
Here’s a simple view to generate the pdf.
#view.py
import cStringIO as StringIO
import ho.pisa as pisa
from django.http import HttpResponse
from django.template.loader import render_to_string
def my_view(request, *args, **kwargs):
html = render_to_string('some_template.html', RequestContext(request, {
'title': 'This is a test PDF document'
}))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
response = HttpResponse(result.getvalue(), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=document.pdf'
return response
Enjoy
