GitHub:https://github.com/Kozea/WeasyPrint 官方文档:https://weasyprint.readthedocs.io/en/latest/index.html
安装
按照官方的说明文档,我们总结下步骤:
1、安装了Python,并且添加了环境变量PATH。
2、更新下 pip:python -m pip install —upgrade pip setuptools
3、安装 WeasyPrint:python -m pip install WeasyPrint
4、安装 GTK+ 库:根据Python的版本安装对应的GTK版本(现在都是64了吧) GTK 下载地址
- 如果不知道自己安装的是32还是64,可以使用 python —version —version 查看
- 注意:添加 GTK安装路径到环境变量。
5、使用 python -m weasyprint http://weasyprint.org weasyprint.pdf 测试下是否安装成功。
- 默认是下载到C:\Users\Administrator目录下,如果不知道,用everything工具搜下。
- 或者直接使用命令 WHERE weasyprint.pdf 找到文件路径。
如果出现报错: OSError: dlopen() failed to load a library: cairo / cairo-2 ,可能是以下两个文件夹没有添加环境变量,我们使用以下命令找到文件目录:
WHERE libcairo-2.dll
WHERE zlib1.dll
结果如下
C:\msys2\mingw64\bin\libcairo-2.dll
C:\Program Files\GTK3-Runtime Win64\bin\zlib1.dll
我们上面的两个目录(注意是文件所在的目录)添加到环境变量PATH即可。当然,如果你的
简单实例
weasyprint http://weasyprint.org /tmp/weasyprint.pdf
这就完了吗?
肯定不是,如果只是单纯的转换一个网页,直接用浏览器的打印功能,然后另存为PDF就可以了。没必要绕个这么大的弯子来做这件事。
我们希望用它来做自动化、批量化、个性化的任务。例如一次将几十个html链接转换成PDF,或者每个html页面我还想加一些自定义的内容进去等等。
要实现这些东西,我们首先要熟悉WeasyPrint的几个概念。
构建HTML对象
生成PDF文件前,首先需要构建一个HTML对象,HTML对象可以通过url链接、文件路径,或者是HTML文档字符串指定
from weasyprint import HTML
HTML('../foo.html') # Same as …
HTML(filename='../foo.html')
HTML('http://weasyprint.org') # Same as …
HTML(url='http://weasyprint.org')
HTML(sys.stdin) # Same as …
HTML(file_obj=sys.stdin)
生成pdf文件只需要调用html对象的write_pdf方法。一个最简单的例子:
from weasyprint import HTML
HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf')
你还可以自定义样式
from weasyprint import HTML, CSS
HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf',
stylesheets=[CSS(string='body { font-family: serif !important }')])
当然不仅可以生成PDF,也可以生成PNG图片, 只需要调用 html.write_png(“filename.png”)。
Document对象
此外,HTML对象的render()方法返回一个document对象,通过docuemnt对象可以拿到所有页码(page)数据,这样你就可以获取指定页的数据来生成PDF或者将多个HTML的document对象合并成一个PDF文件。
例如,将每页单独生成一张图片
from weasyprint import HTML
html1 = HTML("https://foofish.net/base64.html")
document = html1.render()
for i, page in enumerate(document.pages):
document.copy([page]).write_png('page_%s.png' % i)
例如:将两个链接整个生成一个PDF文件
from weasyprint import HTML
html1 = HTML("https://foofish.net/base64.html")
html2 = HTML("https://foofish.net/python-wsgi.html")
pages = []
pages.extend(html1.render().pages)
pages.extend(html2.render().pages)
HTML(string="").render().copy(pages).write_pdf("foofish.pdf")
更多实用方法可以参考文档。