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 @ 2020-09-30 11:48  lesten  阅读(354)  评论(0)    收藏  举报