【问题标题】:Codec error when generating pdf via pdfkit通过 pdfkit 生成 pdf 时的编解码器错误
【发布时间】:2020-01-20 06:48:38
【问题描述】:

我正在尝试通过 pdfkit 库从 html 模板生成 pdf 文件。一切正常,期待使用本地字母表中的某些特殊字符的情况(例如,在这种情况下为“Ž”)。然后出现如下错误:

UnicodeEncodeError: 'latin-1' codec can't encode character '\u017d' in 位置 57:序数不在范围内(256)

代码:

if request.form['action'] == 'Print':
    config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
    rendered = render_template('pdf.html')

    pdf = pdfkit.from_string(rendered, False, configuration=config)

    response = make_response(pdf)
    response.headers['Content-Type'] = 'application/pdf'

    response.headers['Content-Disposition'] = 'attachment; filename='filename.pdf'

    return response

html模板中也定义了charset:<meta charset="utf-8">

您知道什么是根本原因以及如何解决它吗?

【问题讨论】:

    标签: python flask character-encoding pdf-generation


    【解决方案1】:

    问题已解决,我将 .\Python\Lib\http\server.py 中的 'latin-1' 更改为 'utf-8':

        def send_header(self, keyword, value):
        """Send a MIME header to the headers buffer."""
        if self.request_version != 'HTTP/0.9':
            if not hasattr(self, '_headers_buffer'):
                self._headers_buffer = []
            self._headers_buffer.append(
                ("%s: %s\r\n" % (keyword, value)).encode('utf-8', 'strict'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      相关资源
      最近更新 更多