【Python】使用pdfkit報錯:OSError: wkhtmltopdf exited with non-zero code 1. error:
阿新 • • 發佈:2021-01-13
技術標籤:PythonpdfkitOSErrorwkhtmltopdfexited withnon-zero code 1
在工作自動化過程中,有時需要使用Python的pdfkit包將URL或者str等轉換成pdf檔案,今天使用如下程式碼在將str轉換為pdf時,
程式碼如下:
options = {
'page-size':'Letter','margin-top':'0.75in','margin-right':'0.75in',
'margin-bottom':'0.75in','margin-left':'0.75in','encoding':"UTF-8",
'custom-header' : [('Accept-Encoding','gzip')],
'cookie': [('cookie-name1','cookie-value1'),('cookie-name2','cookie-value2'),],
'outline-depth':10,
}
path_wk = r"D:\wkhtmltopdf\bin\wkhtmltopdf.exe" #wkhtmltopdf安裝位置
config = pdfkit.configuration(wkhtmltopdf = path_wk)
pdfkit.from_string(html_str, r"output.pdf" ,configuration=config,options=options)
發生了報錯:報錯OSError: wkhtmltopdf exited with non-zero code 1. error:
為解決這個問題,在網上尋找了好久解決方案,一直沒找到合適的方法,好在最終通過探索發現我這裡報這個錯誤原因是:我的html_str變數是從某個網頁的html檔案複製過來的,而該html中包含css檔案,而我本地沒有該css檔案,從而導致將該str轉化為pdf時報錯。
解決方法:知道了問題的原因之後就比較好解決問題呢,我這邊是在複製html時,直接不復制帶有css部分的即可,只複製需要的文字部分內容。