python输出pdf文档的实例

时间:2021-05-22

python导出pdf,参考诸多资料,发现pdfkit是效果比较好的。

故下载后进行了实现,多次失败后终于成功了,现将其中经验总结如下:

"""需要安装pdfkit,另外需要安装可执行文件wkhtmltopdf.exe,pdfkit核心命令是调用wkhtmltopdf.exe实现转pdf有三个接口:pdfkit.from_urlpdfkit.from_stringpdfkit.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)

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

以上这篇python输出pdf文档的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章