python html(文件/url/html字符串)转pdf

安装库

pip install pdfkit

第二步
下载程序wkhtmltopdf
https://wkhtmltopdf.org/downloads.html

下载7z压缩包 解压即可, 无需安装
在这里插入图片描述
解压后结构应该是这样, 我喜欢放在项目里, 相对路径引用(也可以使用绝对路径, 放其他地方)
在这里插入图片描述


import pdfkit

# 将 wkhtmltopdf.exe程序 路径
path_wkthmltopdf = './wkhtmltox/bin/wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)


def url_to_pdf(url, to_file):
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_url(url, to_file, configuration=config, options={'encoding': 'utf-8'})
    print('完成')


# 这里传入我知乎专栏文章url,转换为pdf
# url_to_pdf(r'https://m.zhijiao.cn/newsmini/detail/102201', './招生简章/102201.pdf')

# html文件转pdf
def file_to_pdf(path, to_file):
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_file(path, to_file, configuration=config, options={'encoding': 'utf-8'})
    print('完成')


# file_to_pdf('./123.html', './xxx/123.pdf')
pdf_err_counts = 0
# html字符串转pdf
def string_to_pdf(string, to_file):
    global pdf_err_counts
    # 生成pdf文件,to_file为文件路径
    try:
        pdfkit.from_string(string, to_file, configuration=config, options={'encoding': 'utf-8'})
    except Exception as e:
        pdf_err_counts += 1
        print('生成pdf失败', pdf_err_counts, e)

最好每个都像string_to_pdf函数一样, 捕获一下错误, 可以使程序更健壮, 避免转换失败导致程序停止(其他没写因为我没用, 懒得写)

参考: https://www.zhihu.com/tardis/zm/art/94608155?source_id=1005
转换效果参考文章中有, 我觉得还不错, 就是有点慢。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦中千秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值