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

yipeiwu_com6年前Python基础

前提:

安装xhtml2pdf https://pypi.python.org/pypi/xhtml2pdf/
下载字体:微软雅黑;给个地址:https://www.jb51.net/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,原因不明。

相关文章

Python字符串匹配算法KMP实例

本文实例讲述了Python字符串匹配算法KMP。分享给大家供大家参考。具体如下: #!/usr/bin/env python #encoding:utf8 def next(patt...

基于pip install django失败时的解决方法

使用pip安装Django时报错,先是: C:\Users\admin>pip install django Collecting django Retrying (Re...

python模块之subprocess模块级方法的使用

subprocess.run() 运行并等待args参数指定的指令完成,返回CompletedProcess实例。 参数:(*popenargs, input=None, captur...

Python 遍历子文件和所有子文件夹的代码实例

Python 遍历子文件和所有子文件夹的代码实例

最近看ECShop到网上找资料,发现好多说明ECShop的文件结构不全面,于是想自己弄个出来。但这是个无聊耗时的工作,自己就写了个Python脚本,可以递归遍历目录下的所有文件和所有子目...

python实现定时同步本机与北京时间的方法

本文实例讲述了python实现定时同步本机与北京时间的方法。分享给大家供大家参考。具体如下: 这段python代码首先从www.beijing-time.org上获取标准的北京时间,然后...