【问题标题】:minimal example of how to export a jupyter notebook to pdf using nbconvert and PDFExporter()如何使用 nbconvert 和 PDFExporter() 将 jupyter notebook 导出为 pdf 的最小示例
【发布时间】:2016-09-27 19:26:25
【问题描述】:

我正在尝试使用 nbconvert 从笔记本单元格中导出 jupyter 笔记本的 pdf 副本。我已经阅读了documentation,但我只是找不到一些基本代码来实际执行 nbconvert 命令并导出为 pdf。

我能够做到这一点,但我希望有人能填补最后的空白。

from nbconvert import PDFExporter
notebook_pdf = PDFExporter()
notebook_pdf.template_file = '../print_script/pdf_nocode.tplx'

注意确定如何从这里开始实际创建 pdf。

任何帮助将不胜感激。

【问题讨论】:

  • 请注意,我发现了一个简单的方法来解决这个问题,只需使用命令行魔法:!jupyter nbconvert --to pdf --template pdf_nocode.tplx ../mgmt_notebook05092016.ipynb 但知道如何使用从 nbconvert api 执行 pdf 创建似乎仍然很好。

标签: pdf jupyter-notebook nbconvert


【解决方案1】:

我不是专家,但设法让这个工作。关键是您需要对笔记本进行预处理,这将允许您使用PDFExporter.from_notebook_node() 函数。这将为您提供字节格式的 pdf_data,然后可以将其写入文件:

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert import PDFExporter

notebook_filename = "notebook.ipynb"

with open(notebook_filename) as f:
    nb = nbformat.read(f, as_version=4)

ep = ExecutePreprocessor(timeout=600, kernel_name='python3')

ep.preprocess(nb, {'metadata': {'path': 'notebooks/'}})

pdf_exporter = PDFExporter()

pdf_data, resources = pdf_exporter.from_notebook_node(nb)

with open("notebook.pdf", "wb") as f:
    f.write(pdf_data)
    f.close()

值得注意的是,ExecutePreprocessor 需要资源字典,但我们在本例中没有使用它。

【讨论】:

  • 它工作正常。感谢您的信息。我只是对表格和代码单元格的轮廓有疑问。是否可以从 PDF 中删除代码单元格?如何修复这个布局问题?谢谢
  • 调用 f.close() 是不必要的,因为您使用的是 with 块。
【解决方案2】:

以下是将 .ipynb 文件转换为 .html 的 rest api 发布:http://URL/export/<id> 获取:http://URL/export/<id> 将返回一个 id.html

import os
from flask import Flask, render_template, make_response
from flask_cors import CORS
from flask_restful import reqparse, abort, Api, Resource
from nbconvert.exporters import HTMLExporter

exporter = HTMLExporter()

app = Flask(__name__)
cors = CORS(app, resources={r"/export/*": {"origins": "*"}})
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('path')
notebook_file_srv = '/path of your .ipynb file'

def notebook_doesnt_exist(nb):
    abort(404, message="Notebook {} doesn't exist".format(nb))


class Notebook(Resource):
    def get(self, id):
        headers = {'Content-Type': 'text/html'}
        return make_response(render_template(id + '.html'), 200, headers)


    def post(self, id):
        args = parser.parse_args()
        notebook_file = args['path']

        notebook_file = notebook_file_srv + id + '.ipynb'

        if not os.path.exists(notebook_file):
            return 'notebook \'.ipynb\' file not found', 404
        else:
            nb_name, _ = os.path.splitext(os.path.basename(notebook_file))
            # dirname = os.path.dirname(notebook_file)
            output_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates')

            output_path = os.path.join(output_path, '{}.html'.format(nb_name))

            output, resources = exporter.from_filename(notebook_file)

            f = open(output_path, 'wb')
            f.write(output.encode('utf8'))
            f.close()
            return 'done', 201


api.add_resource(Notebook, '/export/<id>')

if __name__ == '__main__':
    app.run(debug=True)

【讨论】:

  • OP 要求在 Jupyter 笔记本的上下文中使用 PDF 导出器。您在烧瓶应用程序的上下文中提供了一个 HTML 导出器。
猜你喜欢
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2020-06-28
  • 2019-03-05
相关资源
最近更新 更多