简体   繁体   English

Juypter Notebook:将 output 保存为 pdf

[英]Juypter Notebook: Saving output as pdf

I am using Jupyter Notebook.我正在使用 Jupyter 笔记本。 Is there a possibility to save all the output in a PDF-file?是否有可能将所有 output 保存在 PDF 文件中?

For example, I have this code:例如,我有这个代码:

print('Hello World')

Which outputs:哪个输出:

Hello World

I just want to save the output as PDF but not the code.我只想将 output 保存为 PDF 而不是代码。 Can I do this somehow automated?我可以以某种方式自动化吗?

Background: I wrote an analytics report using a loop which outputs some graphs, equations and other printed statements.背景:我使用循环输出一些图表、方程式和其他打印语句来编写分析报告。 I am now looking for a solution to save this outputed results somehow.我现在正在寻找以某种方式保存此输出结果的解决方案。 I saw that fpdf seems to be a possibility but I could not install it.我看到fpdf似乎是一种可能性,但我无法安装它。 So, I would like to got for another solution.所以,我想得到另一个解决方案。

Thanks in advance!提前致谢!

You can try this你可以试试这个

Step 1步骤1

Save the notebook, using the below snippet or from the Jupyter notebook使用以下代码段或 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']
    )

Step 2第2步

Convert the notebook to HTML excluding the Code cells将笔记本转换为 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()

Usage用法

Save notebook保存笔记本

import time

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

Call the output_HTML function调用output_HTML function

output_HTML(current_file, output_file)

Next, you can convert the HTML output to pdf either from the browser(if you are using Chrome)接下来,您可以从浏览器将 HTML output 转换为 pdf(如果您使用的是 Chrome)

It may not be an efficient solution, but can be done in this way also.这可能不是一个有效的解决方案,但也可以通过这种方式完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM