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

编程入门 行业动态 更新时间:2024-10-24 19:21:18

python html(文件/url/html<a href=https://www.elefans.com/category/jswz/34/1771434.html style=字符串)转pdf"/>

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

安装库

pip install pdfkit

第二步
下载程序wkhtmltopdf
.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'', './招生简章/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函数一样, 捕获一下错误, 可以使程序更健壮, 避免转换失败导致程序停止(其他没写因为我没用, 懒得写)

参考: =1005
转换效果参考文章中有, 我觉得还不错, 就是有点慢。

更多推荐

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

本文发布于:2023-12-03 12:30:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1655365.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   文件   html   python   url

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!