1. 程式人生 > 程式設計 >python輸出pdf文件的例項

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',options=options)

這是我個人試驗的程式碼,效果如下。簡單記錄,實為興趣。

python輸出pdf文件的例項

以上這篇python輸出pdf文件的例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。