python--jupyter notebook 转化为PDF教程

安装

需要安装pdfkit:pip install pdfkit
wkhtmltopdf的下载地址:https://www.qqtn.com/down/315109.html 【普通下载】
安装之后将目录文件放在环境变量中:C:\Program Files\wkhtmltopdf\bin(查看自己的安装目录)

使用

然后在python文件中粘贴如下代码:

# 执行命令行的包 也可以用os.system
import subprocess

import pdfkit

# 获得ipynb文件
inputfile = r'E:\python\yl_site\youlan_project\jupyter_project\test_pdf.ipynb'
# 截取ipynb前面的名字,并保留一份html临时文件
# 这份文件会在转换过程中需要
# 因为我是利用jupyter对于html的支持,使用pdfkit对html文件进行转换
temp_html = inputfile[0:inputfile.rfind('.')]+'.html'
# 转换ipynb文件为html
# 调用了ipython接口
command = 'ipython nbconvert --to html ' + inputfile
# shell端执行command
subprocess.call(command, shell=True)
print('============success===========')
# 拼接一个pdf名字
output_file = inputfile[0:inputfile.rfind('.')]+'.pdf'
# 大杀器出场,pdfkit直接将html转换成pdf
path_wk = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' #安装位置
config = pdfkit.configuration(wkhtmltopdf = path_wk)
pdfkit.from_file(temp_html, output_file, configuration=config)
# pdfkit.from_string("hello world","1.pdf",configuration=config)#字符转PDF
# 删除html临时文件
subprocess.call('rm '+temp_html, shell=True)


搞定。。。

有什么问题请留言,如果觉得有用请点赞支持下。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值