Python

Python - HTML转换为PDF文件wkhtmltopdf

2018-08-22  本文已影响1人  红薯爱帅

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. 安装中文字体

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

https://askubuntu.com/questions/959152/how-can-i-install-the-latest-wkhtmltopdf-on-ubuntu-16-04

上一篇下一篇

猜你喜欢

热点阅读