最近接到一个客户需求,要求将学生的考试结果分析表格和图表导出到PDF。表格使用的是普通的table,图表引用了https://www.chartjs.org/ 遇到的问题详见wkhtmltopdf chartjsphp
在网上查了下先后端均可以将html生成pdf,考虑到实现效果以及效率,最后决定将转化工做在服务端使用PHP完成。本着最好不要额外安装软件的原则,搜索事后分别尝试了 TCPDF MPDF FPDF html2pdf 等等。可是实现效果都与预期差距较大。最后不得不尝试须要额外安装的wkhtmltopdf。html
引用 官网 介绍:wkhtmltopdf是wkhtmltox中的一个工具,另外一个是wkhtmltoimage。它们是开源(LGPLv3)命令行工具,使用Qt WebKit渲染引擎将HTML呈现为PDF和各类图像格式。它们不须要显示或显示服务。值得一提的是谷歌浏览器chrome也使用的是Qt WebKit渲染引擎。linux
安装是在docker中进行的,使用开源项目docker-lnmp。但该php使用的是alpine版本,遂把镜像改回默认的debian版本,后因为客户使用的是centos,又单独下载了centos7的镜像。laravel
# wget https://downloads.wkhtmltopdf.org/0.12/0.12.5/wkhtmltox_0.12.5-1.jessie_amd64.deb # dpkg -i wkhtmltox_0.12.5-1.jessie_amd64.deb
这里安装会提示缺乏依赖信息,其余信息能够直接经过apt-get install进行安装,可是这两个须要注意下 :git
dpkg: dependency problems prevent configuration of wkhtmltox: wkhtmltox depends on libpng12-0; however: Package libpng12-0 is not installed. wkhtmltox depends on libssl1.0.0; however: Package libssl1.0.0 is not installed.
这两个包直接去仓库中搜索安装便可,而后再次执行安装命令,就会成功安装了github
# dpkg -i wkhtmltox_0.12.5-1.jessie_amd64.deb # wkhtmltopdf -V # wkhtmltopdf --enable-forms https://www.baidu.com baidu.pdf
# wget https://downloads.wkhtmltopdf.org/0.12/0.12.5/wkhtmltox-0.12.5-1.centos7.x86_64.rpm # rpm -ivh wkhtmltox-0.12.5-1.centos7.x86_64.rpm
正常系统安装并update后会提示缺乏依赖信息:web
error: Failed dependencies: fontconfig is needed by wkhtmltox-1:0.12.2.1-1.x86_64 freetype is needed by wkhtmltox-1:0.12.2.1-1.x86_64 libpng is needed by wkhtmltox-1:0.12.2.1-1.x86_64 libjpeg is needed by wkhtmltox-1:0.12.2.1-1.x86_64 libX11 is needed by wkhtmltox-1:0.12.2.1-1.x86_64 libXext is needed by wkhtmltox-1:0.12.2.1-1.x86_64 libXrender is needed by wkhtmltox-1:0.12.2.1-1.x86_64 xorg-x11-fonts-Type1 is needed by wkhtmltox-1:0.12.2.1-1.x86_64 xorg-x11-fonts-75dpi is needed by wkhtmltox-1:0.12.2.1-1.x86_64
这里直接按照提示的安装包就能够了chrome
# yum install fontconfig freetype libpng libjpeg libX11 libXext libXrender xorg-x11-fonts-Type1 xorg-x11-fonts-75dpi
而后再次执行安装命令,就会成功安装了docker
# rpm -ivh wkhtmltox-0.12.5-1.centos7.x86_64.rpm # wkhtmltopdf -V # wkhtmltopdf --enable-forms https://www.baidu.com baidu.pdf
这里须要注意的是部分系统可能会抛出异常
QXcbConnection: Could not connect to display Aborted (core dumped)
这里须要安装xvfb而后使用xvfb运行shell
# xvfb-run wkhtmltopdf --enable-forms https://www.baidu.com baidu.pdf
导出的pdf中文会有乱码,能够将windows系统c盘system32目录下的Fonts里面的字体拷贝到linux的/usr/share/fonts下从新运行就能够了
wkhtmltopdf是跨平台的软件,和后端使用那种语言是没有关系的。
PHP有直接能够用的框架https://github.com/KnpLabs/snappy和laravel框架https://github.com/barryvdh/laravel-snappy固然直接使用PHP执行shell也及其简单,但要注意防范webshell。