from tornado import template
loader = template.Loader("/user/Desktop/") # out.html 的路径
content = loader.load("out.html").generate(data=data) # data是向out.html 里渲染的{}数据
config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') # 设置 wkhtmltopdf 路径
pdfkit.from_string(content.decode("utf-8"), "/user/Desktop/out.pdf", configuration=config) # 生成路径/user/Desktop/out.pdf
示例:
baidu.html
为百度公司百度百科的网页源码内容
<!DOCTYPE html> <!--STATUS OK--> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta name="referrer" content="always" /> <meta name="description" content="百度(纳斯达克:BIDU),全球最大的中文搜索引擎、最大的中文网站。百度愿景是:成为最懂用户,并能帮助人们成长的全球顶级高科技公司。“百度”二字,来自于八百年前南宋词人辛弃疾的一句词:众里寻他千百度。这句话描述了词人对理想的执着追求。1999年底,身在美国硅谷的李彦宏看到了中国互联网及中文搜索引擎服务的巨大发展潜力,抱着技术改变世界的梦想,他毅然辞掉硅谷的高薪工作,携搜索引擎专利技术,于 2000年1月1日在中关村创建了百度公司。百度拥有数万名研发工程师,这是中国乃至全球最为优秀的技术团队。这支队伍掌握着世界上最为先进的搜索引擎技术,使百度成为中国掌握世界尖端科学核心技术的中国高科技企业,也使中国成为美国、俄罗斯、和韩国之外,全球仅有的4个拥有搜索引擎核心技术的国家之一。..."> <title>百度(百度公司)_百度百科</title> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg"> <meta name="keywords" content="百度 百度公司 baidu 百度发展简史 百度公司理念 百度财报数据 百度产品手册 百度多语言化 百度建筑设施 百度管理团队 百度百度大事记"> <meta name="image" content="https://bkssl.bdimg.com/cms/static/baike.png"> <script type="text/javascript"> // 配置 PD 监控。 window.alogObjectConfig = { product: '103', page: '103_1', speed: { sample: '0.008' }, monkey: { sample: '1', hid: '1533' }, exception: {
.........等等
loader = template.Loader("/user/Desktop/") # 指定 baidu.html 路径
content = loader.load("baidu.html")
config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') # 设置 wkhtmltopdf 路径
pdfkit.from_string(content.decode("utf-8"), "/user/Desktop/out.pdf", configuration=config) # 生成路径/user/Desktop/out.pdf
生成内容:


安装:wkhtmltopdf
出处:https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf
Installing wkhtmltopdf
ThunderSon edited this page on 4 Dec 2018 · 5 revisions
Visit the wkhtmltopdf home page.
Linux
Download the static binary for your architecture at the wkhtmltopdf downloads list, extract the file to a directory that is in your PATH, such as /opt or /usr/local/bin and run from there.
Debian / Ubuntu
apt-get install wkhtmltopdfFedora / RHEL / CentOS
yum install wkhtmltopdfWindows
Download the installer from the wkhtmltopdf downloads list and add folder with wkhtmltopdf binary to PATH.
Mac
Download the disk image from wkhtmltopdf downloads list and copy the file to a directory where PDFKit can find it. Homebrew is also available, run
brew install Caskroom/cask/wkhtmltopdf.
本文介绍如何利用Python的Tornado模板引擎结合wkhtmltopdf将HTML文件转换为PDF。通过具体示例展示了加载HTML内容、配置wkhtmltopdf路径并最终生成PDF文件的过程。
1166

被折叠的 条评论
为什么被折叠?



