[英]Juypter Notebook: Saving output as pdf
我正在使用 Jupyter 筆記本。 是否有可能將所有 output 保存在 PDF 文件中?
例如,我有這個代碼:
print('Hello World')
哪個輸出:
Hello World
我只想將 output 保存為 PDF 而不是代碼。 我可以以某種方式自動化嗎?
背景:我使用循環輸出一些圖表、方程式和其他打印語句來編寫分析報告。 我現在正在尋找以某種方式保存此輸出結果的解決方案。 我看到fpdf
似乎是一種可能性,但我無法安裝它。 所以,我想得到另一個解決方案。
提前致謝!
你可以試試這個
步驟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
function
output_HTML(current_file, output_file)
接下來,您可以從瀏覽器將 HTML output 轉換為 pdf(如果您使用的是 Chrome)
這可能不是一個有效的解決方案,但也可以通過這種方式完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.