Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Output a PDF, from HTML without doing an HTTP request/response roundtrip on the backend.

View wkhtmltopdf_handler.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 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')
html.write(output.encode("UTF-8"))
 
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(fsock.read(), mimetype='application/pdf')
outfile = 'myfilename.pdf'
response['Content-Disposition'] = 'attachment; filename=%s' % outfile
return response
Owner

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
Something went wrong with that request. Please try again.