当前位置: 首页 > article >正文

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
转换效果参考文章中有, 我觉得还不错, 就是有点慢。


http://www.kler.cn/a/104209.html

相关文章:

  • MobileNetV3
  • 分享个包含各省、市、区的编码数据的在线静态资源脚本
  • PyCharm 安装 cx_Oracle 失败
  • c语言从入门到实战——分支和循环
  • Kubernetes (K8S)概述
  • Kubernetes技术与架构-网络 3
  • 上游服务不可用了,下游服务如何应对?
  • 3682: 【C3】【递推】台阶问题
  • 【Linux Screen命令】Linux用户注销后可长时间运行的命令行
  • React 核心与实战2023版
  • IP地址在网络安全中的关键作用
  • 机器学习之ROC与AUC
  • Linux msend.pl配置
  • mysql 基础知识
  • 【数据结构】数组和字符串(四):特殊矩阵的压缩存储:稀疏矩阵——三元组表
  • JWT的登录认证与自校验原理分析
  • AUTOSAR汽车电子嵌入式编程精讲300篇-基于 CAN 总线的车辆数据采集与远程监控系统研发
  • 一文了解GC垃圾回收
  • 大数据性能测试方案-V1.0
  • 操作系统第二章王道习题_进程与线程_总结易错知识点