1. 程式人生 > >Django 遇到的錯誤:expected str, bytes or os.PathLike object, not _io.TextIOWrapper

Django 遇到的錯誤:expected str, bytes or os.PathLike object, not _io.TextIOWrapper

但是下載出來的pdf有樣式問題,即沒載入進去樣式檔案,pdfkit有提供一個from_file的方法,可以載入多個樣式和一個樣式,即如下簡單的程式碼:

# 單個 CSS 檔案
css = 'example.css'
pdfkit.from_file('file.html', options=options, css=css)

# Multiple CSS files
css = ['example.css', 'example2.css']
pdfkit.from_file('file.html', options=options, css=css)

2、不過如果你寫多了一點程式碼,或者寫錯了就會出現不同的錯誤,而我遇到的錯誤是expected str, bytes or os.PathLike object, not _io.TextIOWrapper,翻譯過來的含義是:期望的STR、位元組或OS.路徑型物件,而不是_io.TextIOWrapper,出現這個錯誤的程式碼如下:

css = ['base.css', 'front.css']
    with open(path + id + '.html', encoding='utf-8') as f:
        pdfkit.from_file(f, path + id + '.pdf', configuration=config, options=options, css=css)

這裡,我通過開啟一個html檔案,在根據開啟的這個html檔案來生成pdf,如果沒有加css屬性倒是可以匯出pdf的,這是不是很鬱悶,加了就報expected str, bytes or os.PathLike object, not _io.TextIOWrapper錯誤,最後終於知道什麼情況了,示例程式碼寫得很清楚了,而且報錯資訊也很清楚,io.TextIOWrapper就是一個檔案開啟來只讀時候的型別,css屬性這樣指定就不是那個方法所需要的型別了。

3、修改程式碼如下即可,直接把html的頁面轉換成pdf便不會報錯了:

css = ['base.css', 'front.css']
pdfkit.from_file(path + id + '.html', path + id + '.pdf', configuration=config, options=options, css=css)

以上內容僅供大家學習參考,謝謝!