Django - pdf response has wrong encoding - xhtml2pdf
Asked Answered
H

1

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?

Harl answered 15/8, 2017 at 8:31 Comment(0)
L
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>
Leasia answered 15/8, 2017 at 9:9 Comment(2)
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 "..." %}Harl
you may try link_callback for add url xhtml2pdf.readthedocs.io/en/stable/… , hope it help youLeasia

© 2022 - 2024 — McMap. All rights reserved.