美文网首页Python
Python - HTML转换为PDF文件wkhtmltopdf

Python - HTML转换为PDF文件wkhtmltopdf

作者: 红薯爱帅 | 来源:发表于2018-08-22 20:08 被阅读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. 安装中文字体

    • 查看目前安装字体: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

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

    相关文章

      网友评论

        本文标题:Python - HTML转换为PDF文件wkhtmltopdf

        本文链接:https://www.haomeiwen.com/subject/gxxuiftx.html