温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用python包pdfkit将HTML转换为PDF

发布时间:2022-04-21 13:41:02 来源:亿速云 阅读:211 作者:iii 栏目:开发技术

本篇内容介绍了“怎么用python包pdfkit将HTML转换为PDF”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

    python包-pdfkit 将HTML转换为PDF

    什么是pdfkit

    pdfkit,把HTML+CSS格式的文件转换成PDF格式文档的一种工具。它就是html转成pdf工具包wkhtmltopdf的Python封装。所以,必须手动安装wkhtmltopdf。

    安装

    首先需要安装 pdfkit 库,使用 pip install pdfkit 命令就好了。
    还需要安装 wkhtmltopdf 工具,本质就是利用这个工具来进行转换,pdfkit 库就是作为接口来调用该工具。
    python版本 3.x,在命令行输入:

    $sudo apt-get install wkhtmltopdf

    Ubuntu系统可以直接使用以下命令安装:

    $sudo yum intsall wkhtmltopdf

    CentOS系统可以直接使用以下命令安装:

    $sudo yum intsall wkhtmltopdf

    使用

    将url生成pdf文件

    不指定wkhtmltopdf,会从系统的默认执行路径下找 wkhtmltopdf

    import pdfkit
    '''将url生成pdf文件'''
    def url_to_pdf(url, to_file):
        pdfkit.from_url(url, to_file,verbose=True)
    url_to_pdf('http://www.baidu.com','out_3.pdf')

    指定 wkhtmltopdf 的位置:

    import pdfkit
    '''将url生成pdf文件'''
    def url_to_pdf(url, to_file):
        config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
        pdfkit.from_url(url, to_file,configuration=config,verbose=True)
    url_to_pdf('http://www.baidu.com','out_3.pdf')
    字符串生成pdf【pdfkit.from_string()函数】
    # 导入库
    import pdfkit
    
    '''将字符串生成pdf文件'''
    def str_to_pdf(string, to_file):
        # 将wkhtmltopdf.exe程序绝对路径传入config对象
        path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
        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')

    报错

    报错OSError: No wkhtmltopdf executable found

    在使用pdfkit.from_string或者pdfkit.from_file或者pdfkit.from_url将字符串、文件或者网页内容转化为pdf时,报错:

    OSError: No wkhtmltopdf executable found

    原因很明显,就是没找到可执行的wkhtmltopdf文件,也就是未找到wkhtmltopdf.exe文件。
    python的pdfkit扩展包使用时需要基于wkhtmltopdf.exe这个可执行文件才可运行,因此需要先安装wkhtmltopdf。
    对于windows系统,可以在(https://wkhtmltopdf.org/downloads.html)下载安装,然后将该程序的执行文件路径添加到环境变量中(这样即可直接用pdfkit扩展包,否则需要在使用pdfkit时,指明该程序的路径)

    Ubuntu系统可以直接使用以下命令安装:

    $sudo apt-get install wkhtmltopdf

    CentOS系统可以直接使用以下命令安装:

    $sudo yum intsall wkhtmltopdf

    “怎么用python包pdfkit将HTML转换为PDF”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI