7

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?

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

7

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>
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • 1
    I tried and it works. The only problem is that it doesn't work with {% static "..." %}. It wants the absolute path. Is there a way how to make it work with relative path or put there an absolute path using shortcut like static? I'm not yet in development mode so my static folders are split into apps so I can't do something like {{ STATIC_ROOT }}{% static "..." %} – Milano Aug 15 '17 at 09:12
  • 1
    you may try `link_callback` for add url http://xhtml2pdf.readthedocs.io/en/stable/usage.html#using-xhtml2pdf-in-django , hope it help you – Brown Bear Aug 15 '17 at 09:23