加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python将html转成PDF的实现代码(包含中文)

发布时间:2020-12-16 19:42:34 所属栏目:Python 来源:网络整理
导读:前提: 安装xhtml2pdf https://pypi.python.org/pypi/xhtml2pdf/ 下载字体:微软雅黑;给个地址:http://www.jb51.net/fonts/8481.html 待转换的文件:1.htm 复制代码 代码如下: meta charset="utf8"/ style type='text/css' @font-face { font-family: "cod

前提:

安装xhtml2pdf https://pypi.python.org/pypi/xhtml2pdf/
下载字体:微软雅黑;给个地址:http://www.aspzz.cn/fonts/8481.html

待转换的文件:1.htm

复制代码 代码如下:

<meta charset="utf8"/>
<style type='text/css'>
@font-face {
        font-family: "code2000";
        src: url("code2000.ttf")
}

html {
     font-family: code2000;
}
</style>
<html>
<body><table>
<tr>
<td>文字</td>
<td>123</td>
</tr>
<tr>
<td>图片</td>
<td><img src="1.jpg"></td>
</tr>
</table></body></html>

html_to_pdf.py程序

复制代码 代码如下:

# -*- coding: utf-8 -*-
import sx.pisa3 as pisa
data= open('1.htm').read()
result = file('test.pdf','wb')
pdf = pisa.CreatePDF(data,result)
result.close()
pisa.startViewer('test.pdf')

说明:xhtml2pdf不能识别汉字,需要在html文件中通过CSS的方式嵌入code2000字体,貌似只能用code2000,原因不明。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读