pdf - 如何使用 nbconvert 和 PDFExporter() 将 jupyter notebook 导出为 pdf 的最小示例

标签 pdf jupyter-notebook nbconvert

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

我能走到这一步,但我希望有人能填补最后的空白。

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

请注意如何从此处开始实际创建 pdf。

如有任何帮助,我们将不胜感激。

最佳答案

我不是专家,但设法让它发挥作用。关键是您需要预处理笔记本,这将允许您使用 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 需要 resources dict,但我们在此示例中不使用它。

关于pdf - 如何使用 nbconvert 和 PDFExporter() 将 jupyter notebook 导出为 pdf 的最小示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732784/

相关文章:

java - 在 java 中使用 itext 填写 pdf 表单有问题

anaconda - 从 Anaconda Navigator 启动的 Jupyter 默认笔记本目录

python - Jupyter Python Markdown : Evaluated Inline code in LaTeX output

python - 如何在 google colaboratory 的笔记本上运行 nbconvert

python - Jupyter Notebook 导出 HTML 深色

python - 如何在 GitHub 页面上托管 iPython nbconvert 幻灯片

javascript - HTML 内联 PDF

php - 如何将可变数据从数组传递到php中的fpdf

C# FileContentResult 文件下载到自定义文件夹中

python - 旋转 Panda DataFrame 的列名