python输出pdf文档

python导出pdf,参考诸多资料,发现pdfkit是效果比较好的。故下载后进行了实现,多次失败后终于成功了,现将其中经验总结如下: 

"""
需要安装pdfkit,另外需要安装可执行文件wkhtmltopdf.exe,
pdfkit核心命令是调用wkhtmltopdf.exe实现转pdf
有三个接口:
pdfkit.from_url
pdfkit.from_string
pdfkit.from_file  需要注意的是,pdfkit主要是用来将html转pdf,所以文件也是html文件或者纯文本文件,其他文件可能失败。
需要用pdfkit.configuration(wkhtmltopdf=path_wk)来说明wkhtmltopdf.exe的安装位置,否则会找不到
options来约定纸张大小,属性'encoding'约定编码,以防乱码
"""
get_cursor = getcursor.GetCursor()
conn = get_cursor.get_native_conn()
cursor = conn.cursor()
sql = 'select * from lease_contract where id = 1'
cursor.execute(sql)
fetchall = cursor.fetchall()
path_wk = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wk)
# 用options来约定编码格式,以防乱码
options = {
    'encoding': 'utf-8'
}
for data in fetchall:
    with open('D:\\testsave.docx', 'w', encoding='utf-8')as f:
        f.write(data[13])
    with open('D:\\testsave.docx', 'r', encoding='utf-8')as f:
        pdfkit.from_file(f, 'D:\\testsave.pdf', configuration=config, options=options)
    pdfkit.from_string(data[13], 'D:\\test.pdf', configuration=config, options=options)

这是我个人试验的代码,效果如下。简单记录,实为兴趣。

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值