zoukankan      html  css  js  c++  java
  • python pdfkit生成PDF

    pdfkit与wkhtmltopdf介绍

    pdfkit

    pdfkit,把HTML+CSS格式的文件转换成PDF格式文档的一种工具。

    wkhtmltopdf

    pdfkit是基于wkhtmltopdf的python封装,支持URL,本地文件,文本内容到PDF的转换,所以使用pdfkit需要下载wkhtmltopdf。

    三步实现自动生成pdf文档

    1.使用pip安装pdfkit

    python 版本 3.x,在命令行输入:

    pip install pdfkit
     
    2.安装wkhtmltopdf.exe文件
    注意:下载后安装,记住安装路径。
     
    3.使用pdfkit库生成pdf文件
    pdfkit可以将网页、html文件、字符串生成pdf文件。
    网页生成 pdf(pdfkit.from_url()
    # 导入库
    import pdfkit
    
    '''将网页生成pdf文件'''
    def url_to_pdf(url, to_file):
        # 将wkhtmltopdf.exe程序绝对路径传入config对象
        path_wkthmltopdf = r'文件路径'
        config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
        # 生成pdf文件,to_file为文件路径
        pdfkit.from_url(url, to_file, configuration=config)
        print('完成')
    
    url_to_pdf(r'url', '输出文件名.pdf')

    html 文件生成 pdf(pdfkit.from_file()

    # 导入库
    import pdfkit
    
    '''将html文件生成pdf文件'''
    def html_to_pdf(html, to_file):
        # 将wkhtmltopdf.exe程序绝对路径传入config对象
        path_wkthmltopdf = r'文件路径'
        config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
        # 生成pdf文件,to_file为文件路径
        pdfkit.from_file(html, to_file, configuration=config)
        print('完成')
    
    html_to_pdf('html文件名.html','输出文件名.pdf')

    字符串生成 pdf(pdfkit.from_string())

    # 导入库
    import pdfkit
    
    '''将字符串生成pdf文件'''
    def str_to_pdf(string, to_file):
        # 将wkhtmltopdf.exe程序绝对路径传入config对象
        path_wkthmltopdf = r'文件路径'
        config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
        # 生成pdf文件,to_file为文件路径
        pdfkit.from_string(string, to_file, configuration=config)
        print('完成')
    
    str_to_pdf('字符串','输出文件名.pdf')
  • 相关阅读:
    第十六天
    第十五天
    STM8L段式液晶驱动器
    STM8L的LCD接口详解及驱动程序
    作为合格的工程师,这些电路图一辈子都得记住!
    双向晶闸管触发电路工作原理图
    3~15伏10A大电流可调稳压电源
    用TL431制作简单充电器电路
    5V USB充电器电路图
    555
  • 原文地址:https://www.cnblogs.com/-wenli/p/12320773.html
Copyright © 2011-2022 走看看