文章目录

web浏览器的js打印在不同浏览器下面的效果有很大差别,对一些精度要求较高的场景很不适合,而且分页控制困难。如果采用pdf打印就比较完美了,目前测试ie和firefox都需要安装pdf阅读器才能支持pdf在线打开和打印,而chrome可以直接支持。

在python下有reportlab可以生成pdf,实用上较为复杂,后来发现了xhtml2pdf,直接转换html到pdf,支持css,实际使用下来发现它并不是完整的html支持,比如position就不支持,但可以通过@frame解决。

下面是一段示例:

test.py:

1
2
3
4
5
6
7
8
from cStringIO import StringIO

import xhtml2pdf.pisa as pisa

pdf = pisa.CreatePDF(open('test.html','rb'),open('test.pdf','wb'))

if not pdf.err:
print "pdf is build"

test.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<html>
<style>

@font-face {
font-family: simsun;
src: url(c:\windows\fonts\simsun.ttc);
}
body{
font-family: simsun;
}

@page {
margin: 1cm;
margin-bottom: 2.5cm;
font-family: simhei;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 2cm;
margin-left: 1cm;
margin-right: 1cm;
height: 1cm;
font-family: simhei;
}
}
</style>
<body>
<div id="footerContent">
This is a 中文 on page #<pdf:pagenumber>
</div>
</body>
</html>

xhtml2pdf默认是不支持中文字体的,通过@font-face可以添加新字体,我在这里添加了一个宋体。<pdf:pagenumber> 是xhtml2pdf的特殊标签,这里指在是在这个位置显示当前页码。

文章目录