python3 csv,txt,html轉成pdf(windows)
阿新 • • 發佈:2018-11-10
一,安裝 pdfkit
pip install pdfkit
二,安裝 wkhtmltopdf
pip install wkhtmltopdf,可以安裝成功,但是無法新增路徑,執行程式依舊會報錯
OSError: No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf
推薦github下載安裝包,手動安裝,網址如下:
https://wkhtmltopdf.org/downloads.html
三,程式碼段
import pdfkit
import os
def csvToPdf():
#這樣就不需要新增環境變量了
path_wk = r"D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
#wkhtmltopdf包 安裝位置
config = pdfkit.configuration(wkhtmltopdf=path_wk)
options = {
'page-size' : 'A2', #頁面大小
'minimum-font-size': 15,
'margin-top': '0.75in', #邊框填充(inch,基本單位)
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8", #編碼
}
file = xxx.csv
filename = os.path.splitext(file)[0 ]
# 方法一
pdfkit.from_file(file,filename + '.pdf',configuration=config,options=options)
os.remove(abspath)
#方法二
with open("file","r") as f:
content = f.readlines
f.close()
a = ""
for i in content:
a = a + i
pdfkit.from_string(a,filename + '.pdf',configuration=config,options=options)
os.remove(abspath)
四,中文識別問題
儘量避免檔名,路徑名帶有中文
本人的csv,txt檔案,均是從資料庫匯出的,公司統一要求,資料庫不會儲存中文,故未處理中文問題
csv轉html,請參考本人另外一篇部落格