Django - pdf response has wrong encoding - xhtml2pdf

为君一笑 提交于 2020-07-08 11:54:12

问题


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:

Do you know how to make it work correctly?


回答1:


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>


来源:https://stackoverflow.com/questions/45689236/django-pdf-response-has-wrong-encoding-xhtml2pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!