Skip to content

Instantly share code, notes, and snippets.

@george-silva
Forked from gmorada/gist:3228519
Created August 1, 2012 16:54
Show Gist options
  • Save george-silva/3228697 to your computer and use it in GitHub Desktop.
Save george-silva/3228697 to your computer and use it in GitHub Desktop.
Helper para gerar relatório em pdf a partir de um html
from django.template.loader import get_template
from django.template import Context
import cStringIO as StringIO
import cgi
import ho.pisa as pisa
def render_to_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)
if not pdf.err:
response = HttpResponse(result.getvalue(), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % 'relatorio.pdf'
return response
return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment