將 HTML/網頁轉換為 PDF
有許多網站不允許下載 pdf 形式的內容,他們或者要求購買高級版本,或者沒有此類 pdf 形式的下載服務。
隻需 3 步即可將網頁/HTML 轉換為 PDF
第1步:下載庫pdfkit
$ pip install pdfkit
第二步:下載wkhtmltopdf
對於 Ubuntu/Debian:
sudo apt-get install wkhtmltopdf
對於 Windows:
(一)下載鏈接:WKHTMLTOPDF
(b)設置:環境變量中的PATH變量設置二進製文件夾。
第三步:下載Python代碼:
(i) 已保存的 HTML 頁麵
import pdfkit
pdfkit.from_file('test.html', 'out.pdf')
(ii) 通過網站 URL 進行轉換
import pdfkit
pdfkit.from_url('https://www.google.co.in/','shaurya.pdf')
(iii) 將文本存儲為 PDF
import pdfkit
pdfkit.from_string('Shaurya GFG','GfG.pdf')
恭喜:您的 pdf 文件將被創建並保存在 python 文件所在的同一目錄中。
雜項知識內容:
1. 您可以傳遞包含多個 URL 或文件的列表:
pdfkit.from_url(['google.com', 'geeksforgeeks.org', 'facebook.com'], 'shaurya.pdf')
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')
2. 將內容保存在變量中
# Use False instead of output path to save pdf to a variable
pdf = pdfkit.from_url('http://google.com', False)
相關用法
- Python HTMLCalendar formatmonth()用法及代碼示例
- Python HTMLCalendar formatyear()用法及代碼示例
- Python HTMLCalendar formatyearpage()用法及代碼示例
- Python HTML轉Markdown用法及代碼示例
- Python Hex轉String用法及代碼示例
- Python Hex String轉Bytes用法及代碼示例
- Python HandCalcs用法及代碼示例
- Python String format()用法及代碼示例
- Python abs()用法及代碼示例
- Python any()用法及代碼示例
- Python all()用法及代碼示例
- Python ascii()用法及代碼示例
- Python bin()用法及代碼示例
- Python bool()用法及代碼示例
- Python bytearray()用法及代碼示例
- Python callable()用法及代碼示例
- Python bytes()用法及代碼示例
- Python chr()用法及代碼示例
- Python compile()用法及代碼示例
- Python classmethod()用法及代碼示例
- Python complex()用法及代碼示例
- Python delattr()用法及代碼示例
- Python dict()用法及代碼示例
- Python dir()用法及代碼示例
- Python divmod()用法及代碼示例
注:本文由純淨天空篩選整理自shaurya uppal大神的英文原創作品 Python Convert Html to PDF。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。