It allows you to create pdf much like normal html code taking advantage of django's template engine. It requires the trml2pdf module from OpenReport and can be used like render_to_response()
. prompt specifies if a "save as" dialog should be shown to the user while filename is the name that the browser will suggest in the save dialog.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from django.http import HttpResponse
from django.template import loader, Context
from trml2pdf import trml2pdf
def pdf_render_to_response(template, context, filename=None, prompt=False):
response = HttpResponse(mimetype='application/pdf')
if not filename:
filename = template+'.pdf'
cd = []
if prompt:
cd.append('attachment')
cd.append('filename=%s' % filename)
response['Content-Disposition'] = '; '.join(cd)
tpl = loader.get_template(template)
tc = {'filename': filename}
tc.update(context)
ctx = Context(tc)
pdf = trml2pdf.parseString(tpl.render(ctx))
response.write(pdf)
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Hi,
You seem to be missing an import line:
from django.template import loader, Context
#
Oops! I stripped too many lines from my original code. I just updated the snippet.
Thank you prio!
#
Please login first before commenting.