首页 > 解决方案 > Juypter Notebook:将输出保存为 pdf

问题描述

我正在使用 Jupyter 笔记本。是否有可能将所有输出保存在 PDF 文件中?

例如,我有这个代码:

print('Hello World')

哪个输出:

Hello World

我只想将输出保存为 PDF,而不是代码。我可以以某种方式自动化吗?

背景:我使用循环编写了一份分析报告,该循环输出一些图表、方程式和其他打印语句。我现在正在寻找以某种方式保存此输出结果的解决方案。我看到这fpdf似乎是一种可能性,但我无法安装它。所以,我想得到另一个解决方案。

提前致谢!

标签: pythonjupyter-notebook

解决方案


你可以试试这个

步骤1

使用以下代码段或 Jupyter 笔记本保存笔记本

from IPython.display import Javascript
from nbconvert import HTMLExporter
import codecs
import nbformat

def save_notebook():
    display(
        Javascript("IPython.notebook.save_notebook()"),
        include=['application/javascript']
    )

第2步

将笔记本转换为 HTML,不包括代码单元格

def output_HTML(read_file, output_file):

    exporter = HTMLExporter()
    # read_file is '.ipynb', output_file is '.html'
    output_notebook = nbformat.read(read_file, as_version=4)
    output, resources = exporter.from_notebook_node(output_notebook)
    codecs.open(output_file, 'w', encoding='utf-8').write(output)
    
    with open(output_file, 'r') as html_file:
        content = html_file.read()

    # Get rid off prompts and source code
    content = content.replace("div.input_area {","div.input_area {\n\tdisplay: none;")    
    content = content.replace(".prompt {",".prompt {\n\tdisplay: none;")

    f = open(output_file, 'w')
    f.write(content)
    f.close()

用法

保存笔记本

import time

save_notebook()
time.sleep(10)
current_file = 'Your Python Notebook.ipynb'
output_file = 'Output file Name.html'

调用output_HTML函数

output_HTML(current_file, output_file)

接下来,您可以从浏览器将 HTML 输出转换为 pdf(如果您使用的是 Chrome)

这可能不是一个有效的解决方案,但也可以通过这种方式完成。


推荐阅读