您的位置 首页 php

pdfkit | 利用python实现html文件转pdf

在用jupyter notebook写代码文档的时候,有时需要导出pdf版本,但jupyter会报错。我在想,除了网上的debug方法,还没有其他方案可以生成pdf。

度娘搜了下,很多博客推荐 python 的第三方库pdfkit,可以将 网页、html文件以及字符串 生成pdf文件。

其实也有很多软件提供pdf生成服务,但这样太不python了,那下面就来试试pdfkit怎么用吧!

三步实现自动生成pdf文档:

1.使用pip安装pdfkit库

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

 pip install pdfkit  

安装过程基本不会有啥问题,出现上面的Successfully installed pdfkit-0.6.1提示,说明安装成功了。

2.安装wkhtmltopdf. exe 文件

下载地址:

下载wkhtmltopdf

下载完成后,一路next,将wkhtmltopdf安装好。

务必要记住安装地址,找到wkhtmltopdf.exe文件所在的绝对路径,后面要用到。

我这里是默认路径””C:\Program Files\wkhtmltopdf\ bin \wkhtmltopdf.exe””

安装wkhtmltopdf

3.使用pdfkit库生成pdf文件

前面说过pdfkit可以将 网页、html文件、字符串 生成pdf文件。

  • 网页url生成pdf【pdfkit.from_url()函数】
 # 导入库
import pdfkit

'''将网页url生成pdf文件'''
def url_to_pdf(url, to_file):
    # 将wkhtmltopdf.exe程序绝对路径传入 config 对象
    path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
    config = pdfkit. configuration (wk html topdf=path_wkthmltopdf)
    # 生成pdf文件,to_file为文件路径
    pdfkit.from_url(url, to_file, configuration=config)
    print('完成')

# 这里传入我知乎专栏文章url,转换为pdf
url_to_pdf(r'#39;, 'out_1.pdf')  
  • html文件生成pdf【pdfkit.from_file()函数】
 # 导入库
import pdfkit

'''将html文件生成pdf文件'''
def html_to_pdf(html, 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_file(html, to_file, configuration=config)
    print('完成')

html_to_pdf('sample.html','out_2.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')  

4.结论

本文讲了如何在Python中使用pdfkit库生成pdf文件,非常方便快捷,适合批量自动化操作。

我们看看生成的pdf效果如何:

pdf效果展示

整体页面视觉不错呦,赶快用起来吧!

文章来源:智云一二三科技

文章标题:pdfkit | 利用python实现html文件转pdf

文章地址:https://www.zhihuclub.com/80056.shtml

关于作者: 智云科技

热门文章

网站地图