【问题标题】:xhtml2pdf, cyrillic characters don't workxhtml2pdf,西里尔字符不起作用
【发布时间】:2016-03-13 12:55:42
【问题描述】:

我尝试将 html 转换为 pdf。我使用 xhtml2pdf。 我的代码:

# -*- coding: utf-8 -*-
from xhtml2pdf import pisa
sourceHtml = '<html>' \
             '    <head>' \
             '        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">' \
             '    </head>' \
             '    <body>' \
             '        <p>Русский текст</p>' \
             '    </body>' \
             '</html>'

outputFilename = "test.pdf"

def convertHtmlToPdf(sourceHtml, outputFilename):
    resultFile = open(outputFilename, "w+b")
    pisaStatus = pisa.CreatePDF(sourceHtml, dest=resultFile)#, encoding='UTF-8')
    resultFile.close() 
    return pisaStatus.err

if __name__ == "__main__":
    pisa.showLogging()
    convertHtmlToPdf(sourceHtml, outputFilename)

PDF 已创建,但西里尔字符由黑色方块表示。 我做错了什么?怎么弄好?

【问题讨论】:

    标签: python html pdf pdf-generation xhtml2pdf


    【解决方案1】:
    # -*- coding: utf-8 -*-
    from xhtml2pdf import pisa
    sourceHtml = '<html>' \
                 '    <head>' \
                 '        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">' \
                 '        <style type="text/css">' \
                 '            @page { size: A4; margin: 1cm; }' \
                 '            @font-face { font-family: Arial; src: url(/pathToTTF/arial.ttf); }' \
                 '            p { color: red; font-family: Arial; }' \
                 '        </style>' \
                 '    </head>' \
                 '    <body>' \
                 '        <p>Русский текст</p>' \
                 '    </body>' \
                 '</html>'
    
    outputFilename = "test.pdf"
    
    def convertHtmlToPdf(sourceHtml, outputFilename):
        resultFile = open(outputFilename, "w+b")
        pisaStatus = pisa.CreatePDF(sourceHtml, dest=resultFile, encoding='UTF-8')
        resultFile.close() 
        return pisaStatus.err
    
    if __name__ == "__main__":
        pisa.showLogging()
        convertHtmlToPdf(sourceHtml, outputFilename)
    

    它有效。我必须将测试样式设置为 html 标记。

    【讨论】:

    • 你到底做了什么?你只添加了&lt;style&gt;标签?
    • 不仅如此,在
    • 也许每个支持西里尔字母的字体都可以正常工作。谢谢!
    猜你喜欢
    • 2011-12-06
    • 2016-06-15
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多