I wanted to render a template to a pdf file. So I looked this, and found the following code:
def write_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(
html.encode("UTF-8")), result, encoding='UTF-8')
if not pdf.err:
return http.HttpResponse(result.getvalue(),
mimetype='application/pdf', )
return http.HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
It works perfectly, but I am not able to change the filename. If I start the download of this file, firefox says "1.pdf" is downloaded. So here is my question: How can i change the filename of the rendered template? I looked this up, but I haven't found an answer.. (maybe I'm just too stupid^^)
Thank you very much for your help
You're very close. You just need to set the Content-Disposition
of your response:
def write_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(
html.encode("UTF-8")), result, encoding='UTF-8')
if not pdf.err:
response = http.HttpResponse(result.getvalue(),
mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=whatever.pdf'
return response
return http.HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))