zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    对指定文件生成数字摘要的MD5工具类
    shell脚本学习积累笔记(第一篇)
    java项目打成jar包时引用了第三方jar,此时我们该如何解决呢
    分享关于学习new BufferedWriter()方法时常遇到的一个无厘头的问题
    WebService学习整理(一)——客户端三种调用方式整理
    TZOJ 挑战题库随机训练02
    TZOJ 挑战题库随机训练01
    TZOJ 2943 Running Median(动态中位数)
    TZOJ 3927 Circular Sequence(环形最大子段和)
    TZOJ 3698 GCD depth(数学)
  • 原文地址:https://www.cnblogs.com/lesten/p/13753798.html
Copyright © 2011-2022 走看看