登录
    Technology changes quickly but people's minds change slowly.

利用Python将网页保存为PDF文件

技术宅 破玉 2166次浏览 0个评论

环境简介

wkhtmltopdf可以直接把任何一个可以在浏览器中浏览的网页直接转换成一个pdf,首先说明一下它不是一个python库,而是一个把html页面转换成pdf的一个软件,我们需要在系统上安装它。
Ubuntu 16.04 安装wkhtmltopdf

$ sudo apt-get install wkhtmltopdf

然后Python需要使用这个软件需要再安装一个库

sudo pip3 install pdfkit

pdfkit使用示例

参考文档
一个简单的例子:

import pdfkit

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

你也可以传递一个url或者文件名列表:

pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf')
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')

其他使用方式请参照pdfkit参考文档

参考代码

def html2pdf(url,tag,name,value):
	html=requests.get(url).content
	bsObj=BeautifulSoup(html,'html.parser')
	title=bsObj.h1
	content=bsObj.find(tag,{name:value})
	content.insert(1,title)
	filename=content.h1.get_text()
	html=html_template.format(content=content)
	html = html.encode("utf-8")
	with open(filename+'.html', 'wb') as f:
		f.write(html)
	pdfkit.from_file(filename+'.html',filename+'.pdf',options=options)

项目地址:
html2pdf


华裳绕指柔, 版权所有丨如未注明 , 均为原创|转载请注明利用Python将网页保存为PDF文件
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址