python3 csv,txt,html转成pdf(windows)

一,安装 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,请参考本人另外一篇博客

猜你喜欢

转载自blog.csdn.net/weixin_42367527/article/details/82698458