1. Installation
sudo apt-get update
sudo apt-get install wkhtmltopdf -y
sudo pip install pdfkit
2. Using wkhtmltopdf without X server
wkhtmltopdf needs a X server. If you're running your application on a VPS, you probably don't have one installed. The solution is install a "virtual" X server.
Using a virtual X server
apt-get install xvfb
printf '#!/bin/bash\nxvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf -q $*' > /usr/bin/wkhtmltopdf.sh
chmod a+x /usr/bin/wkhtmltopdf.sh
ln -s /usr/bin/wkhtmltopdf.sh /usr/local/bin/wkhtmltopdf
wkhtmltopdf http://baidu.com baidu.pdf
Recommend solution
Upgrade to 0.12.3 form 0.9.9
cd ~
wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.3/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
tar vxf wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
cp wkhtmltox/bin/wk* /usr/local/bin/
3. 安装中文字体
- 查看目前安装字体:fc-list
- 下载所需字体,例如msyh.ttf
- mkdir /usr/share/fonts/zh_CN
- mv msyh.ttf /usr/share/fonts/zh_CN
- 执行fc-cache -fv
- 查看是否安装成功:fc-list,查看是已安装
4. demo
def save_pdf(htmls, file_name):
options = {
'quiet': '',
'page-size': 'Letter',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'custom-header': [
('Accept-Encoding', 'gzip')
],
'cookie': [
('cookie-name1', 'cookie-value1'),
('cookie-name2', 'cookie-value2'),
],
'outline-depth': 10,
}
pdfkit.from_string(htmls, file_name, options=options)
5. reference
-
wkhtmltopdf org
https://wkhtmltopdf.org/usage/wkhtmltopdf.txt -
Using wkhtmltopdf without X server
https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server -
python wkhtmltopdf使用与注意事项
http://kaito-kidd.com/2015/03/12/python-html2pdf/
https://askubuntu.com/questions/959152/how-can-i-install-the-latest-wkhtmltopdf-on-ubuntu-16-04
网友评论