For generating PDF, you may use xhtml2pdf library.
The function returns response object, you just pass the name of your template, context data and pdfname.
def fetch_resources(uri, rel):
"""
Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc.
`uri` is the href attribute from the html link element.
`rel` gives a relative path, but it's not used here.
"""
if uri.startswith(settings.MEDIA_URL):
path = os.path.join(settings.MEDIA_ROOT,
uri.replace(settings.MEDIA_URL, ""))
elif uri.startswith(settings.STATIC_URL):
path = os.path.join(settings.STATIC_ROOT,
uri.replace(settings.STATIC_URL, ""))
else:
path = os.path.join(settings.STATIC_ROOT,
uri.replace(settings.STATIC_URL, ""))
if not os.path.isfile(path):
path = os.path.join(settings.MEDIA_ROOT,
uri.replace(settings.MEDIA_URL, ""))
if not os.path.isfile(path):
raise UnsupportedMediaPathException(
'media urls must start with %s or %s' % (
settings.MEDIA_ROOT, settings.STATIC_ROOT))
return path
def render_to_pdf_response(template_name, context=None, pdfname='test.pdf'):
file_object = HttpResponse(mimetype='application/pdf')
file_object['Content-Disposition'] = 'attachment; filename=%s' % pdfname
template = get_template(template_name)
html = template.render(Context(context))
pisa.CreatePDF(html.encode("UTF-8"), file_object , encoding='UTF-8',
link_callback=fetch_resources)
return file_object
Here is installation instructions: https://pypi.python.org/pypi/xhtml2pdf/