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文檔的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答