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')
  • 相关阅读:
    codeforces 707D-(DFS+bitset)
    codeforces Educational Codeforces Round 16-E(DP)
    codeforces 597C (树状数组+DP)
    codeforces #round363 div2.C-Vacations (DP)
    Codeforces Round #365 (Div. 2)-D Mishka and Interesting sum(树状数组)
    codeforces round367 div2.C (DP)
    June Challenge 2018 Division 2
    Codeforces Round #487 (Div. 2)
    Educational Codeforces Round 45 (Rated for Div. 2)
    [Offer收割]编程练习赛63
  • 原文地址:https://www.cnblogs.com/lesten/p/13753798.html
Copyright © 2011-2022 走看看