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

本文详细介绍如何使用Python将CSV文件转换为PDF格式,包括安装必要的库如pdfkit和wkhtmltopdf,解决路径配置问题,以及提供代码示例。同时,文章还提到了处理中文识别的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,安装 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,请参考本人另外一篇博客
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值