Skip to content

Instantly share code, notes, and snippets.

@tjzango
Created September 19, 2019 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjzango/2ba012423af5e8f34e5dfe3613c67c34 to your computer and use it in GitHub Desktop.
Save tjzango/2ba012423af5e8f34e5dfe3613c67c34 to your computer and use it in GitHub Desktop.
Render to pdf
# Util .py
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
# usage.py
def print_report(request, *args):
template = get_template('path')
context = {
'report': 'never mind
}
template.render(context)
pdf = render_to_pdf('diagnosis/report_print.html', context)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = "report_for {} {}.pdf".format(key, instance.order.customer)
content = "inline; filename='%s'" % filename
download = request.GET.get("download")
if download:
content = "attachment; filename='%s'" % filename
response['Content-Disposition'] = content
return response
return HttpResponse("Not found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment