【问题标题】:Django - pdf response has wrong encoding - xhtml2pdfDjango - pdf响应编码错误 - xhtml2pdf
【发布时间】:2018-01-23 03:51:51
【问题描述】:

我正在我的 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:

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

【问题讨论】:

    标签: django pdf encoding diacritics xhtml2pdf


    【解决方案1】:

    尝试将字体网址添加到您的 html 中,不要忘记替换路径和名称

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

    【讨论】:

    • 我试过了,效果很好。唯一的问题是它不适用于 {% static "..." %}。它想要绝对路径。有没有办法让它与相对路径一起工作,或者使用像静态这样的快捷方式放置一个绝对路径?我还没有处于开发模式,所以我的静态文件夹被分成应用程序,所以我不能做像 {{ STATIC_ROOT }}{% static "..." %}
    • 你可以试试link_callback添加网址xhtml2pdf.readthedocs.io/en/stable/…,希望对你有帮助
    猜你喜欢
    • 2020-09-05
    • 2013-05-30
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2020-08-31
    • 2012-01-09
    相关资源
    最近更新 更多