首页 > 解决方案 > 如何编码此字符串以将其导出为 PDF

问题描述

我正在尝试将包含 UTF-8 字符的字符串导出到 PDF。我已将我的代码简化为以下代码,以便能够重现它:

source = """<html>
            <style>
                @font-face {
                font-family: Preeti;
                src: url("preeti.ttf");
                }

                body {
                font-family: Preeti;
                }
            </style>
            <head>
                <meta http-equiv="content-type" content="text/html; charset=utf-8">
            </head>
            <body>
                This is a test <br/>
                       सरल
            </body>
        </html>"""

from xhtml2pdf import pisa
from io import StringIO, BytesIO

bytes_result = BytesIO()
pisa.CreatePDF(source, bytes_result, encoding='UTF-8')
result = StringIO(bytes_result.getvalue().decode('UTF-8', 'ignore'))

f = open('test.pdf', 'wt', encoding='utf-8')
f.write(result.getvalue())

生成以下PDF:

在此处输入图像描述

我从互联网上尝试了很多解决方案,但我无法正确解决。知道我错过了什么吗?

标签: python-3.xutf-8python-3.6python-unicodepisa

解决方案


推荐阅读