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 = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)
if not pdf.err:
return http.HttpResponse(result.getvalue(), mimetype='application/pdf')
except Exception('PDF error')
All non-latin symbols are not showing correctly, the template and view are saved using utf-8 encoding.
I've tried saving view as ANSI and then to user unicode(html,"UTF-8"), but it throws TypeError.
Also I thought that maybe it's because the default fonts somehow do not support utf-8 so according to pisa documentation I tried to set fontface in template body in style section.
That still gave no results.
Does any one have some ideas how to solve this issue?
This does work for me:
If you are calling createPDF instead of the pisaDocument method, you can use
I faced the same problem with cyrillic characters.
The solution contained two steps: 1. Point out the font file in your HTML file
2. Give "pisa" root path (so that it find font file by relative path) in my case it was something like this
because fonts were placed at PATH_TO_DJANGO_PROJECT/files/arial.ttf
Try replacing
with
Or checkout this answer to html to pdf for a Django site?
You need to modify your django template. Add a new font face in the stylesheet that will link to a font file with characters used in your document. And that font file must be accessible from your server (under Ubuntu you can find files with fonts in /usr/share/fonts/truetype/ directory). For example:
Then if you have next HTML code:
you can display that text in DejaMono font with this CSS rule:
This works for me when I generate PDF documents with cyrillic characters.