Search code examples
djangopdfencodingdiacriticsxhtml2pdf

Django - pdf response has wrong encoding - xhtml2pdf


I'm working on an invoice PDF generator on my Django website. I use xhtml2pdf. It seems to be working but encodings is not correct. There are wrong signs/characters when I use diacritics.

This is a view:

def render_to_pdf(template_src, context_dict):
    template = get_template("pdf/pdf.html")
    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 HttpResponse(result.getvalue(), content_type='application/pdf; encoding="utf-8"')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

And this is the html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
  </head>
  <body>
    <p>Č š ž Ž x y ľ ĺ ó</p>
  </body>
</html>

This is the generated pdf: enter image description here

Do you know how to make it work correctly?


Solution

  • Try add font urls to your html, don't forget to replace path and name

    <!DOCTYPE html>
    <html>
      <head>
          <style>
            @font-face {
            font-family: FreeSans;
            src: url("/usr/share/fonts/truetype/freefont/FreeSans.ttf");
            }
    
            body {
            font-family: FreeSans;
            }
        </style>  
        <meta charset="UTF-8">
        <title>title</title>
      </head>
      <body>
        <p>Č š ž Ž x y ľ ĺ ó</p>
      </body>
    </html>