python 记录网页 生成pdf

以前经常有网页想保存或者收藏的需求,有时候收藏了,等到想去看的时候,哎,网页已过期!!!  脸上笑嘻嘻,心里 。。。

偶然看到这个 https://zhuanlan.zhihu.com/p/94608155,记录下

他这里是 Windows 平台,我 Mac 上试了下,如果你是 windows平台 移步他那边。

因为我 Mac 上 装了两个版本  所以 用pip3

pip3 install pdfkit

安装完成以后 下载 pdfkit, 这里下载  https://wkhtmltopdf.org/downloads.html

如果你觉得这个地址下载慢 我也传了一个,在这里 https://download.csdn.net/download/lilang66/12901692

下载 安装后直接用就好了

复制代码
# 导入库
import pdfkit
import platform

print(platform.system())

def getToolPath():
    if platform.system() == "Windows":
        return r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
    elif platform.system() == "Darwin":
        return r''

'''将网页url生成pdf文件'''
def url_to_pdf(url, to_file):
    # 将wkhtmltopdf.exe程序绝对路径传入config对象
    path_wkthmltopdf = getToolPath()
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_url(url, to_file, configuration=config)
    print('完成')

# 这里传入我知乎专栏文章url,转换为pdf
# url_to_pdf(r'https://zhuanlan.zhihu.com/p/69869004', 'out_1.pdf')
url_to_pdf(r'https://www.baidu.com', 'out_1.pdf')

'''将html文件生成pdf文件'''
def html_to_pdf(html, to_file):
    # 将wkhtmltopdf.exe程序绝对路径传入config对象
    path_wkthmltopdf = getToolPath()
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_file(html, to_file, configuration=config)
    print('完成')

# html_to_pdf('sample.html','out_2.pdf')

'''将字符串生成pdf文件'''
def str_to_pdf(string, to_file):
    # 将wkhtmltopdf.exe程序绝对路径传入config对象
    path_wkthmltopdf = getToolPath()
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_string(string, to_file, configuration=config)
    print('完成')

# str_to_pdf('This is test!','out_3.pdf')
复制代码

 

posted @   lesten  阅读(335)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示