首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

新年开篇之python中html页面转化成pdf

通常在工作中经常会遇见将某些好的html数据转换成PDF,便于存储和阅读,今天就来看看这个简单的html转换PDF模块:pdfkit

模块安装

安装python-pdfkit模块:

$ pip install pdfkit

操作系统安装wkhtmltopdf模块:

Debian/Ubuntu:

$ sudo apt-get install wkhtmltopdf

提醒:在Debian / Ubuntu版本中有减少功能(因为它编译没有wkhtmltopdf QT补丁),如添加大纲,头,页脚,toc等使用这个选项,你应该从wkhtmltopdf网站安装静态二进制文件,或者你可以使用这个脚本.

使用

简单的例子:

import pdfkitpdfkit.from_url('http://google.com', 'out.pdf') #获取在线的url数据进行转换生成本地out.pdf文档pdfkit.from_file('test.html', 'out.pdf') #获取本地html文件进行转换生成本地out.pdf文档pdfkit.from_string('Hello!', 'out.pdf') #将输入的文本转换生成本地out.pdf文档

可以将多个url或者文件放到一个列表中进行转换:

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

打开文件读取数据进行转换:

with open('file.html') as f: pdfkit.from_file(f, 'out.pdf')

如果你想进一步生成 PDF, 你可以传递一个参数:

# 使用 False 代替输出保存一个可变的PDFpdf = pdfkit.from_url('http://google.com', False)

你可以指定 wkhtmltopdf 选项. 在名称中你可以删除 ‘–’. 如果选择没有值, 使用None, Falseor“”,对于重复的选择(允许,cookie,自定义标题,发布,postfile,运行脚本,替换) 在多个值的时候你可能会用到列表或者元组进行存储 (列入自定义头文件授权信息) 你需要两个元组存放 (看看以下例子).

options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'custom-header' : [ ('Accept-Encoding', 'gzip') ] 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'no-outline': None}pdfkit.from_url('http://google.com', 'out.pdf', options=options)

默认情况, PDFKit 会显示wkhtmltopdf全部输出 . 如果你不想使用它,可以通过静态配置来选择:

options = { 'quiet': '' }pdfkit.from_url('google.com', 'out.pdf', options=options)

由于wkhtmltopdf命令语法,toc和cover选项必须单独指定。如果你需要覆盖之前,使用cover_first选项:

toc = { 'xsl-style-sheet': 'toc.xsl'}cover = 'cover.html'pdfkit.from_file('file.html', options=options, toc=toc, cover=cover)pdfkit.from_file('file.html', options=options, toc=toc, cover=cover, cover_first=True)

你可以在使用css选项转换文件或字符串时指定外部css文件.

警告:这是在wkhtmltopdf这个错误的解决方法。您应该首先尝试使用-user-style-sheet选项。.

# Single CSS filecss = 'example.css'pdfkit.from_file('file.html', options=options, css=css)# Multiple CSS filescss = ['example.css', 'example2.css']pdfkit.from_file('file.html', options=options, css=css)

你可以在html中元素标签中传递任何选项:

body = """ Hello World! """pdfkit.from_string(body, 'out.pdf') #with --page-size=Legal and --orientation=Landscape配置

每个api调用都需要一个可选的配置参数。这应该是pdfkit.configuration()api调用的一个实例。它将配置选项作为初始参数。可用的选项是:

wkhtmltopdf-二进制wkhtmltopdf存放位置. 默认pdfkit使用系统默认的存放位置

meta_tag_prefix-特定元标记的前缀 - 默认情况下为pdfkit-

例子- 针对wkhtmltopdf不在默认$PATH路径下的情况:

config = pdfkit.configuration(wkhtmltopdf='/opt/bin/wkhtmltopdf')pdfkit.from_string(html_string, output_file, configuration=config)

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180222G05D3500?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券