本文同步發表於我的微信公衆號,掃一掃文章底部的二維碼或在微信搜索 極客導航 即可關注。
概況
在日常工作生活中,有時候需求是將HTML轉成PDF,網上一些工具也有很多,不過一般都是在線轉換或者一次只能轉一張,甚至一些工具需要充值…
今天我們python寫一個HTML轉成PDF程序,對於一些會Python的小夥伴來說,自己寫的程序,自由度比較高。
準備工作
我們今天用到的庫是:pdfkit
安裝:pdfkit
pip install pdfkit
在自己的操作系統上安裝:wkhtmltopdf
Ubuntu
sudo apt-get install wkhtmltopdf
Mac
brew install Caskroom/cask/wkhtmltopdf
CentOS
sudo yum intsall wkhtmltopdf
windows
下載地址:https://wkhtmltopdf.org/downloads.html
並配置系統環境變量
###開始轉換
import pdfkit
pdfkit.from_url('https://www.jianshu.com','out.pdf')
看似效果還不錯,並且還支持很多
本地的Html文件
import pdfkit
pdfkit.from_file('jianshu.htm','out.pdf')
字符串
import pdfkit
pdfkit.from_string('HelloWorld','out.pdf')
打開文件
import pdfkit
with open('jianshu.htm','r') as f:
pdfkit.from_file(f,'out.pdf')
多個HTML同時轉換
import pdfkit
pdfkit.from_url(['https://www.jianshu.com/','https://www.baidu.com/'],'out.pdf')
#pdfkit.from_file(['jianshu.htm','jianshu1.htm'],'out.pdf')
自定義參數
如果上面還滿足不了你的需求,一些參數可以自定義:
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)
這個工具很強大,裏面有很多參數和方法,不過一般需求基本已經能搞定。如果還有深度需求大家可以參考下面的文檔:
pdfkit文檔:https://pypi.org/project/pdfkit/
wkhtmltopdf參數:http://www.kongzhizhen.com/%E7%94%9F%E6%B4%BB/282/
下面的是我的公衆號二維碼圖片,歡迎關注。