python下将html转换为pdf工具,个人认为pdfcrowd与pdfkit比较好用。这里主要介绍mac下使用方法,其他操作系统类似。
一、pdfcrowd
1.pdfcrowd提供在线转换,网址:pdfcrowd官网,如下图。

2.同时也提供了python的API接口,首先需要安装一下。
1 | pip install pdfcrowd |
然后还需要在其官网上注册,获取key,然后就可以愉快也使用了,使用方法也相当地简单。
3.使用示例
(1)将url转换为pdf文件,期中your_name是你的注册名,your_key是注册后获取的key。免费的有使用次数限制,好像是每天30次。付费则没限制。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import pdfcrowd import sys try: # create the API client instance client = pdfcrowd.HtmlToPdfClient('your_name', 'your_key') # run the conversion and write the result to a file client.convertUrlToFile('http://www.example.com', 'example.pdf') except pdfcrowd.Error as why: # report the error sys.stderr.write('Pdfcrowd Error: {}\n'.format(why)) # rethrow or handle the exception raise |
(2)将本地html转换为pdf文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import pdfcrowd import sys try: # create the API client instance client = pdfcrowd.HtmlToPdfClient('your_name', 'your_key') # run the conversion and write the result to a file client.convertFileToFile('本地html路径', 'example.pdf') except pdfcrowd.Error as why: # report the error sys.stderr.write('Pdfcrowd Error: {}\n'.format(why)) # rethrow or handle the exception raise |
需要了解详细接口参数,使用方法,可以看一下官网doc。
二、pdfkit
1.pdfkit其实是wkhtmltopdf的Python封装,所以需要先安装wkhtmltopdf,方法:
(1)到官网下载安装:https://wkhtmltopdf.org/downloads.html
(2)或者:
1 | brew install Caskroom/cask/wkhtmltopdf |
参考:Python快速将HTML转PDF ,妈妈再也不会担心我不会转PDF了
(3)安装pdfkit
1 | pip install pdfkit |
2.使用示例
(1)本地html
1 2 | import pdfkit pdfkit.from_file('jianshu.htm','out.pdf') |
(2)字符串
1 2 | import pdfkit pdfkit.from_string('HelloWorld','out.pdf') |
(3)打开文件
1 2 3 | import pdfkit with open('jianshu.htm','r') as f: pdfkit.from_file(f,'out.pdf') |
(4)多个html文件同时转换
1 2 3 4 | import pdfkit pdfkit.from_url(['https://www.jianshu.com/','https://www.baidu.com/'],'out.pdf') #pdfkit.from_file(['jianshu.htm','jianshu1.htm'],'out.pdf') |
(5)自定义参数设置,如果有特殊需要,可以在这里设置参数。
1 2 3 4 5 6 7 8 9 10 11 | import pdfkit options={ 'page-size':'A4',#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('https://www.jianshu.com/','out1.pdf', options=options) |
官网上也有详细介绍:Python – Convert HTML Page to PDF。
三、总结
pdfkit用之前需要下载wkhtmltopdf这个软件,然后还需要设置它的路径,过程相对繁琐一点,如果打包程序,还需要把wkhtmltopdf打包进去,而且比较大,有50M+。
而pdfkit的转换效果与pdfcrowd差不多,个人更喜欢简单易操作的pdfcrowd。