xhtml2pdf,西里尔文字符不起作用 [英] xhtml2pdf, cyrillic characters don't work

查看:146
本文介绍了xhtml2pdf,西里尔文字符不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to convert html to pdf. I use xhtml2pdf. My code:

# -*- 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,但西里尔文字符用黑色方块表示。
我做错了什么?如何使它正确?

PDF is created, but the Cyrillic characters are represented by black squares. What I'm doing wrong? How to make it right?

推荐答案

# -*- 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标记。

It works. I had to set test style to html tag.

这篇关于xhtml2pdf,西里尔文字符不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆