-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.