python函数大全pdf_Python生成PDF(pdfkit库)

三步实现自动生成pdf文档:

使用pip安装pdfkit库

python 版本 3.x,在命令行输入:

pip3 install pdfkit

安装wkhtmltopdf.exe文件

注:pdfkit是基于wkhtmltopdf的python封装,所以需要安装wkhtmltopdf.exe。wkhtmltopdf是轻量级软件,非常很容易安装。

489c3aff61bd

下载完成后,一路next,将 wkhtmltopdf 安装好。

务必要记住安装地址,找到wkhtmltopdf.exe文件所在的绝对路径,后面要用到。

我这里是默认路径C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe

489c3aff61bd

使用pdfkit库生成pdf文件

前面说过pdfkit可以将网页、html文件、字符串生成pdf文件。

网页生成 pdf【pdfkit.from_url()函数】

# 导入库

import pdfkit

'''将网页生成pdf文件'''

def url_to_pdf(url, to_file):

# 将wkhtmltopdf.exe程序绝对路径传入config对象

path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'

config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

# 生成pdf文件,to_file为文件路径

pdfkit.from_url(url, to_file, configuration=config)

print('完成')

# 这里传入我知乎专栏文章url,转换为pdf

url_to_pdf(r'https://zhuanlan.zhihu.com/p/69869004', 'out_1.pdf')

html 文件生成 pdf【pdfkit.from_file()函数】

# 导入库

import pdfkit

'''将html文件生成pdf文件'''

def html_to_pdf(html, to_file):

# 将wkhtmltopdf.exe程序绝对路径传入config对象

path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'

config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

# 生成pdf文件,to_file为文件路径

pdfkit.from_file(html, to_file, configuration=config)

print('完成')

html_to_pdf('sample.html','out_2.pdf')

字符串生成 pdf【pdfkit.from_string()函数】

# 导入库

import pdfkit

'''将字符串生成pdf文件'''

def str_to_pdf(string, to_file):

# 将wkhtmltopdf.exe程序绝对路径传入config对象

path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'

config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

# 生成pdf文件,to_file为文件路径

pdfkit.from_string(string, to_file, configuration=config)

print('完成')

str_to_pdf('This is test!','out_3.pdf')

结论

本文讲了如何在 Python 中使用pdfkit库生成pdf文件,非常方便快捷,适合批量自动化操作。

我们看看生成的 pdf 效果如何:

489c3aff61bd

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值