转换本地HTML到pdf

系统要求

python3.4以上版本, 不支持python2.x

C:\Users\o>python -V
Python 3.6.0

准备工具

既然是把 html 文件转为 pdf,那么也要有相应的库支持, wkhtmltopdf 就是一个非常的工具,它可以用适用于多平台的 html 到 pdf 的转换,pdfkit 是 wkhtmltopdf 的Python封装包。首先安装好下面的依赖包

pip install requests
pip install beautifulsoup4
pip install pdfkit

安装 wkhtmltopdf

Windows平台直接在 http://wkhtmltopdf.org/downloads.html 下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程序的执行路径加入到系统环境 $PATH 变量中,否则 pdfkit 找不到 wkhtmltopdf 就出现错误 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行进行安装

$ sudo apt-get install wkhtmltopdf  # ubuntu
$ sudo yum intsall wkhtmltopdf      # centos

转换本地HTML到pdf

将上面的路径加入到环境变量中。

用法

比如:

path_wk = r'D:\software\soft\wkhtmltox\bin\wkhtmltopdf.exe'  # 安装位置
config = pdfkit.configuration(wkhtmltopdf=path_wk)

pdfkit.from_file('test1.html', r'h:\u\a.pdf', configuration=config)
pdfkit.from_url('http://www.sejie22.com', r'h:\u\a.pdf', configuration=config)
pdfkit.from_string("hello",  r'h:\u\a.pdf', configuration=config)

不过最后,发现没有必要,因为我不是做的批量爬取数据操作。我只是需要将本地文件夹中大量图片,做到HTML中,然后通过HTML转为pdf文件。

而我发现了浏览器中其实可以转换(适用单个),然后,下面是做将大量图片存入到HTML中的操作:

# coding=utf-8
from __future__ import unicode_literals
import pdfkit
import os

PATH = "H:\考研相关文档\889"
list_dir = os.listdir(PATH)   #获取文件加下所有的文件名列表
sorted(list_dir)       #排序



html=""
for i in list_dir:
    src = "E:/codes/loadtemp/img/"+i
    img = "<img src='%s'></img>" % format(src)
    html=html+img



html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body,*{
            margin:0;
            padding:0;
            width:700px;
        }
        img{
            width:694px;
            margin: 0 auto;
            padding:0;
            margin-bottom: 10px;
            border:3px solid #ddd;
        }
    </style>
</head>
<body>
    <div id="container" style="margin:0 auto;width:700px;border:1px solid #eee;">
        '%s'
    </div>
</body>
</html>
""" % format(html)

f = open('test.html', 'wb')
html = bytes(html, encoding='utf-8')
f.write(html)
f.close()

转换本地HTML到pdf

即可。

 

 

 


参考:https://github.com/lzjun567/crawler_html2pdf/tree/master/pdf

参考:https://blog.****.net/xc_zhou/article/details/80952168

工具下载地址:https://wkhtmltopdf.org/downloads.html


作者:无涯明月