html转pdf

蛋疼的需求需要用到将html页面专成pdf供下载:

需要:wkhtmltopdf、pdfkit

1、去wkhtmltopdf官网下载tar包(https://wkhtmltopdf.org/downloads.html

2、安装依赖包

yum install zlib fontconfig freetype X11 libs libX11 libXext libXrender libpng*

 

3、将刚刚下载的托到服务器、解压

tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz

得到一个目录wkhtmltox,把wkhtmltopdf复制到/usr/bin目录,更改所有者,并增加可执行属性

 

4、安装

sudo cp wkhtmltox/bin/wkhtmltopdf /usr/bin/

sudo chown root:root /usr/bin/wkhtmltopdf

sudo chmod +x /usr/bin/wkhtmltopdf

 

 

5、测试一下

wkhtmltopdf http://www.baidu.com /opt/baidu.pdf

"Done"表明顺利完成,当前目录下出现一个baidu.pdf,打开,正是百度首页。

6 pip isntall pdfkit

 

7使用

    import pdfkit

    pdfkit.from_url('http://google.com', 'out.pdf')
    pdfkit.from_file('test.html', 'out.pdf')
    pdfkit.from_string('Hello!', 'out.pdf')

 可以传递一个打开的文件:

with open('file.html') as f:
        pdfkit.from_file(f, 'out.pdf')

 你可以制定所有的 wkhtmltopdf 选项 <http://wkhtmltopdf.org/usage/wkhtmltopdf.txt>. 你可以移除选项名字前面的 '--' .如果选项没有值, 使用None, Falseor * 作为字典值:

options = {
        'page-size': 'Letter',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'no-outline': None
    }

    pdfkit.from_url('http://google.com', 'out.pdf', options=options)

 默认情况下, PDFKit 将会显示所有的 wkhtmltopdf 输出. 如果你不想看到这些信息,你需要传递一个 quiet选项:

 options = {
        'quiet': ''
        }

    pdfkit.from_url('google.com', 'out.pdf', options=options)

 

posted @ 2018-03-30 10:12  想做土匪的书生  阅读(193)  评论(0编辑  收藏  举报