Centos7安装Wkhtmltopdf -- nodejs将html转pdf

wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar xvfJ wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
cd wkhtmltox/bin
sudo cp ./wkhtmltopdf /usr/bin/wkhtmltopdf
# 测试
wkhtmltopdf http://www.baidu.com ./test.pdf

运行过程可能提示缺少一些动态库,直接安装即可。

字体方块或乱码

需要增加中文字体

拷贝Windows下的微软雅黑字体文件(C:\Windows\fonts下)到/usr/share/fonts/msyh下,没有需要新建。

yum install -y fontconfig mkfontscale

cd /usr/share/fonts/msyh
mkfontscale
mkfontdir
fc-cache -fv
source /etc/profile

执行 fc-list :lang=zh 可看到字体已经安装

nodejs调用

npm install wkhtmltopdf

// URL
wkhtmltopdf('http://google.com/', { pageSize: 'letter' })
  .pipe(fs.createWriteStream('out.pdf'));

// HTML文件
wkhtmltopdf(fs.createReadStream('index.html'), {output:'out.pdf'});

更多用法参考官网:https://wkhtmltopdf.org/usage/wkhtmltopdf.txt