Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Last active December 18, 2015 01:29
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 kezabelle/49a1ca6d035a6fa1fdf9 to your computer and use it in GitHub Desktop.
Save kezabelle/49a1ca6d035a6fa1fdf9 to your computer and use it in GitHub Desktop.
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')
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
@kezabelle
Copy link
Author

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