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 pdf return None def convert_html_to_pdf(source_html, output_filename, context): # open output file for writing (truncated binary) result_file = open(output_filename, "w+b") template = get_template(source_html) html = template.render(context) # convert HTML to PDF pisa_status = pisa.CreatePDF( html, # the HTML to convert dest=result_file) # file handle to recieve result # close output file result_file.close() # close output file # return False on success and True on errors return pisa_status.err