Python模块之pdfkit

# 1.安装依赖
pip install python-docx  #Python下的Microsoft Word 2007工具
pip install PyPDF2  #Python下的PDF工具
pip install requests #网络请求
pip install beautifulsoup4 #用于操作 html 数据
pip install pdfkit #wkhtmltopdf 的Python封装包

2.安装wkhtmltopdf并添加至环境变量
sudo apt install wkhtmltopdf

3.pdfkit用法
pdfkit.from_url('http://google.com', 'out.pdf')  #从URL生成
pdfkit.from_file('test.html', 'out.pdf')  #从文件生成
pdfkit.from_string('Hello!', 'out.pdf')  #从字符串生成

config_kit = pdfkit.configuration(wkhtmltopdf=r"E:\install\wkhtmltopdf\bin\wkhtmltopdf.exe")
pdfkit.from_string(response.text, 'confirmation_page.pdf', configuration=config_kit)


pdfkit + wkhtmltopdf

Medivh_
2017.12.04 21:47:52
字数 245
阅读 2,012
更多关注:
http://www.mknight.cn

wkhtmltopdf
关于wkhtmltopdf的简介:

wkhtmltopdf主要用于HTML生成PDF。
pdfkit是基于wkhtmltopdf的python封装,支持URL,本地文件,文本内容到PDF的转换,其最终还是调用wkhtmltopdf命令。是目前接触到的python生成pdf效果较好的。
pdfkit
关于pdfkit的简介:
Python和wkhtmltopdf使用webkit引擎将html转变为PDF文件。

Intsall
setup 1
yum
yum install wkhtmltopdf
如果yum找不到,可以手动下载tar.xz文件
wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
cd wkhtmltox/bin
cp ./* /usr/sbin/
setup 2
pip install pdfkit
setup 3
[root@xxx tmp]# wkhtmltopdf -V
wkhtmltopdf 0.12.4 (with patched qt)
使用
input 方式
支持url/file/string的导入。
import pdfkit

pdfkit.from_url(‘http://google.com’, ‘out.pdf’)
pdfkit.from_file(‘test.html’, ‘out.pdf’)
pdfkit.from_string(‘Hello!’, ‘out.pdf’)
支持list
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’)
options
自定义设置

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,
‘outline-depth’: 10,
}

pdfkit.from_url(‘http://google.com’, ‘out.pdf’, options=options)
引用css

Single CSS file

css = ‘example.css’
pdfkit.from_file(‘file.html’, options=options, css=css)

Multiple CSS files

css = [‘example.css’, ‘example2.css’]
pdfkit.from_file(‘file.html’, options=options, css=css)
支持中文字符
需要找一台有安装了中文字体的电脑复制一份字体文件(就是/usr/share/fonts下的文件),然后操作就可以了。
需要在html的字符集设置为utf8

参考资料
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逻辑痒痒挠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值