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')
  • 相关阅读:
    最近纠结致死的一个java报错java.net.SocketException: Connection reset 终于得到解决
    分享:fastjson 1.1.28 发布,Java 的 JSON 库
    Google Code Jam
    firefox 17.0 编包记(fedora 17)
    中文分词文献列表 Bibliography of Chinese Word Segmentation
    ThriftUsageC++ Thrift Wiki
    try thrift
    SENNA
    Ghostscript: Ghostscript Downloads
    DHCP简介
  • 原文地址:https://www.cnblogs.com/lesten/p/13753798.html
Copyright © 2011-2022 走看看