使用xhtml2pdf将unicode模板转换为pdf时遇到麻烦

bee*_*bek 3 python unicode flask xhtml2pdf

我在html页面中使用了unicode,该页面在html页面中正确显示。但是,当使用xhtml2pdf将其转换为html时,它会在unicode中生成黑色的实心方形框。除UTF-8设置外,是否还有一些Unicode设置。我不认为它的unicode问题。

# convert HTML to PDF
pisaStatus = pisa.CreatePDF(
        StringIO(sourceHtml.encode('utf-8')),                 
        dest=resultFile)
Run Code Online (Sandbox Code Playgroud)

完整的py代码:

# -*- coding: utf-8 -*-

from xhtml2pdf import pisa
from StringIO import StringIO

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

                body {
                font-family: Preeti;
                }
            </style>
            <body>
                This is a test <br/>
                       ???
            </body>
        </html>"""

# Utility function
def convertHtmlToPdf(source):
    # open output file for writing (truncated binary)

    pdf = StringIO()
    pisaStatus = pisa.CreatePDF(StringIO(source.encode('utf-8')), pdf)

    # return True on success and False on errors
    print "Success: ", pisaStatus.err
    return pdf

# Main program
if __name__=="__main__":
    print pisa.showLogging()
    pdf = convertHtmlToPdf(source)
    fd = open("test.pdf", "w+b")
    fd.write(pdf.getvalue())
    fd.close()
Run Code Online (Sandbox Code Playgroud)

生成的pdf文件

我什至需要包含字体吗?

bee*_*bek 5

其部分解决。提供字体的绝对路径,即

    <style>
        @font-face {
        font-family: Preeti;
        src: url("c:/static/fonts/preeti.ttf");
        }

        body {
        font-family: Preeti;
        }
    </style>  
Run Code Online (Sandbox Code Playgroud)

现在又出现了另一个问题。我混合了文本,部分使用unicode,部分使用普通的Font(我认为应该说普通字体:D),因为字体已被覆盖,现在普通的Fonts出现在矩形框中。在这种情况下为空框。