Create a gist now

Instantly share code, notes, and snippets.

Output a PDF, from HTML without doing an HTTP request/response roundtrip on the backend.
# imports ...
from subprocess import call
from uuid import uuid4
from django.template.loader import render_to_string
from django.http import HttpResponse
request_uuid = str(uuid4())
output_pdf = '/tmp/output-%s.pdf' % request_uuid
destination_html = '/tmp/output-%s.html' % request_uuid
with open(destination_html, 'w') as html:
output = render_to_string('some stuff')
command = '%(wkhtmltopdf)s %(cmd_opts)s file://%(html)s %(pdf)s' % {
'wkhtmltopdf': settings.WKHTMLTOPDF, # location of the binary
'html': destination_html,
'pdf': output_pdf,
'cmd_opts': '--disable-javascript',
call(command, shell=True)
assert os.path.exists(output_pdf) == True, "unable to find %s" % output_pdf
with open(output_pdf, "rb") as fsock:
response = HttpResponse(, mimetype='application/pdf')
outfile = 'myfilename.pdf'
response['Content-Disposition'] = 'attachment; filename=%s' % outfile
return response

Note to self: used in this comment as a response to this one in this thread about PDF utils.

Is extracted from an otherwise internal, horribly custom app.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment