Django - pdf响应编码错误 - xhtml2pdf

时间:2017-08-15 08:31:47

标签: django pdf encoding diacritics xhtml2pdf

我在Django网站上处理发票PDF生成器。我使用xhtml2pdf。它似乎工作但编码不正确。当我使用变音符号时,有错误的符号/字符。

这是一个观点:

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))

这是html:

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

这是生成的pdf: enter image description here

你知道如何让它正常工作吗?

1 个答案:

答案 0 :(得分:3)

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>