python - Juypter Notebook:将输出保存为 pdf
问题描述
我正在使用 Jupyter 笔记本。是否有可能将所有输出保存在 PDF 文件中?
例如,我有这个代码:
print('Hello World')
哪个输出:
Hello World
我只想将输出保存为 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
函数
output_HTML(current_file, output_file)
接下来,您可以从浏览器将 HTML 输出转换为 pdf(如果您使用的是 Chrome)
这可能不是一个有效的解决方案,但也可以通过这种方式完成。
推荐阅读
- python - 批处理脚本-Python
- facebook - 通过 APP 广告帐户在经过身份验证的用户的帖子上增加帖子或创建广告
- sql - 如何更正此代码?我正在尝试根据案例获取日期函数
- spring - 我们可以在一个事务下在 DynamoDB 中保留两个不同的表实体吗
- java - 向 mikrotik 客户端发送配置文件更改命令时出错
- java - 如何实现单个 JUnit 测试用例之间的公共数据共享
- java - Java中的ISO 9797-1 MAC算法3和填充方法1示例?
- celery-task - 使用 celery Group 时如何在子任务实例中获取组 ID?
- sql-server - MSSQL:查询表中所有数据子集的可重用方式
- javascript - 使用 __mocks__ 手动模拟不起作用