why
前两天,同事遇到一个产品需求,一个比较复杂的web报表页面,支持下载成pdf功能。考虑实现方案时,大概有以下几种:
- 1、将web版的报表页面制作成相关的模板,下载时,针对这个模板填充数据并完成pdf生成
- 2、将相关的web报表页面直接转换成pdf,并完成下载
方案1的问题是报表的模板比较复杂,而且后面变更的会增加改造成本。这样来看从实现上还是倾向于方案2,那剩下的就是具体的实现方案了,这时发现了一个工具wkhtmltopdf
what
这个软件是基于LGPLv3开源协议,包括两个小工具:wkhtmltopdf和wkhtmltoimage,主要功能将html页面转换成pdf或图片,具体参见官网:http://wkhtmltopdf.org/
wkhtmltopdfandwkhtmltoimageare open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely "headless" and do not require a display or display service.
There is also a C library, if you're into that kind of thing.
how
这个软件提供了Windows、Linux和Mac三个平台的版本,基本满足使用,目前官方最新的稳定版本是0.12.3。
使用方式也比较简单,wkhtmltopdf http://www.google.com google.pdf,详细使用参数见下:
General Options:
--collate Collate when printing multiple copies
--copies <number> Number of copies to print into the pdf
file (default 1)
--extended-help Display more extensive help, detailing
less common command switches
-h, --help Display help
-O, --orientation <orientation> Set orientation to Landscape or Portrait
-s, --page-size <size> Set paper size to: A4, Letter, etc.
--password <password> HTTP Authentication password
-p, --proxy <proxy> Use a proxy
-q, --quiet Be less verbose
--username <username> HTTP Authentication username
-V, --version Output version information an exit
其它
使用过程中,在Linux平台遇到中文乱码问题,具体原因是由于服务器上没有相关字体,解决方案是打开windows c:\Windows\fonts\simsun.ttc拷贝到linux服务器/usr/share/fonts/目录下