Python - HTML转换为PDF文件wkhtmltopdf

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容