You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Jupyter中用%%capture捕获的单元格输出保存为PDF文件

将Jupyter捕获的输出转成JupyterLab格式的PDF

要把%%capture捕获的输出转成和JupyterLab格式一致的静态PDF,核心思路是先把捕获的输出转换成带JupyterLab原生样式的HTML,再将HTML转成PDF。以下是具体实现步骤:

步骤1:捕获输出并生成带样式的HTML

先用capture_output捕获输出,再通过Jupyter的HTMLExporter生成和Lab界面一致的HTML内容:

from IPython.display import capture_output
import nbformat
from nbconvert.exporters import HTMLExporter

# 捕获目标输出
with capture_output() as captured:
    # 替换为你需要捕获输出的代码
    print("示例文本输出")
    import pandas as pd
    df = pd.DataFrame({"A列": [1, 2, 3], "B列": [4, 5, 6]})
    display(df)
    import matplotlib.pyplot as plt
    plt.figure(figsize=(8, 4))
    plt.plot(df["A列"], df["B列"])
    plt.title("示例折线图")
    plt.show()

# 将捕获的输出包装成Notebook单元格
cell = nbformat.v4.new_code_cell()
cell.outputs = captured.outputs

# 使用Lab模板生成带官方样式的HTML
exporter = HTMLExporter(template_name='lab')
html_content, _ = exporter.from_notebook_node(nbformat.v4.new_notebook(cells=[cell]))

# 保存HTML(可选,也可以直接传入PDF转换工具)
with open("output.html", "w", encoding="utf-8") as f:
    f.write(html_content)

步骤2:HTML转PDF(推荐用WeasyPrint)

WeasyPrint对HTML/CSS的支持更贴合现代标准,能完美还原JupyterLab的输出格式:

  1. 先安装依赖:
pip install weasyprint
  1. 执行转换:
from weasyprint import HTML

# 从HTML文件生成PDF
HTML("output.html").write_pdf("captured_output.pdf")

# 也可以直接用内存中的HTML内容生成,无需临时文件
# HTML(string=html_content).write_pdf("captured_output.pdf")

替代方案:用pdfkit(依赖wkhtmltopdf)

如果WeasyPrint安装遇到问题,可以用pdfkit,不过需要额外安装wkhtmltopdf:

  1. 安装依赖:
pip install pdfkit
# 系统级依赖安装:
# Windows:下载wkhtmltopdf安装包并添加到系统PATH
# macOS:brew install wkhtmltopdf
# Linux:sudo apt-get install wkhtmltopdf
  1. 转换代码:
import pdfkit
pdfkit.from_file("output.html", "captured_output.pdf")

关键说明

  • 样式一致性:使用HTMLExporter的lab模板,直接复用JupyterLab的原生CSS,确保PDF输出和Notebook内显示的格式完全一致。
  • 静态输出:所有捕获的内容(包括图表、表格)都会被转换成静态元素(比如matplotlib图表会转成Base64图片嵌入HTML),最终PDF无交互内容,符合需求。

内容的提问来源于stack exchange,提问作者Soliton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:07:07