I\'m trying to generate a pdf from template using this snippet:
def write_pdf(template_src, context_dict):
template = get_template(template_src)
context
I am using xhtml2pdf version 0.2.4 I faced the same issue and I was able to resolve using this encoding:
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
# PDF
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
Then in my views, I have defined like:
def download_pdf(request, pk):
item = get_object_or_404(object, id=pk)
if item:
context ={
'item': item
}
template_name = 'template.html'
pdf = render_to_pdf(template_name, context)
return HttpResponse(pdf, content_type='application/pdf')
else:
messages.info(request, 'Item not found')
return redirect('home')
My HTML:
{% load static %}
{% load humanize %}
{{ item.scientific_name}}