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

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 += 1print('生成pdf失败', pdf_err_counts, e)

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

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

http://www.lryc.cn/news/211699.html

相关文章:

  • Spring概述
  • Linux网卡
  • 【Python机器学习】零基础掌握ElasticNet变量选择回归器
  • 【数据结构】模拟实现Vecotr
  • Qt开发: 利用Qt的charts模块绘制曲线、饼图、柱状图、折线图等各种图表
  • Redis:加速你的应用响应时间,提升用户体验
  • 乐鑫 SoC 内存映射入门
  • 蓝凌EIS智慧协同平台saveImg接口存在任意文件上传漏洞
  • 【SEC 学习】美化 Linux 终端
  • 【Unity小技巧】可靠的相机抖动及如何同时处理多个震动(附项目源码)
  • 【51单片机】51单片机概述(学习笔记)
  • make和new的区别
  • vue3获取页面路径
  • 基于STM32闭环步进电机控制系统设计
  • Java中的队列:各种类型及使用场景
  • MappingMongoConverter原生mongo 枚举类ENUM映射使用的是name
  • Java中的锁:类型,比较,升级与降级
  • STM32:串口轮询模式、中断模式、DMA模式和接收不定长数据
  • 【OJ for Divide and Conquer】OJ题解
  • 使用 Sealos 一键部署 Kubernetes 集群
  • 解读电力系统中的GPS北斗卫星同步时钟系统
  • 原子类:Java并发编程的利器
  • 99%网工都会遇到的经典面试问题
  • html和css中图片加载与渲染的规则是什么?
  • YOLO轻量化改进 , 边缘GPU友好的YOLO改进算法!
  • 第15届蓝桥杯Scratch选拔赛中级(STEMA)真题2023年8月
  • c++二叉树遍历
  • day14_集合
  • 私有云:架构图
  • 在安装和配置DVWA渗透测试环境遇到的报错问题