【问题标题】:Jupyter nbconvert LaTex Export ThemeJupyter nbconvert LaTex 导出主题
【发布时间】:2026-02-09 01:40:01
【问题描述】:

我正在使用 Jupyter Notebook nbconvert(另存为菜单)通过 Latex 导出为 pdf。但是,pdf 文件的格式并不好。例如,一些宽表显示得很好。我希望有一个表格框,可以将其调整为页面的宽度。是否有任何样式、模板可以用来制作漂亮的报告以及如何要求 nbconverter 使用该样式?

这是 Latex 输出:

我想要这样的东西:

【问题讨论】:

    标签: python css latex jupyter-notebook nbconvert


    【解决方案1】:

    看起来 Pandas 在 0.23 版本中获得了._repr_latex_() 方法。您需要设置pd.options.display.latex.repr=True 才能激活它。

    没有乳胶代表:

    用乳胶代表:

    查看options 以获得接近您想要的格式。为了准确匹配您想要的输出,您需要使用自定义的 Latex 模板。


    已编辑以提供有关模板的更多信息:

    Start here 了解有关模板的一般信息。您可以在与笔记本相同的路径中创建.tplx 文件,并在从命令行运行nbconvert 时将其指定为模板:!jupyter nbconvert --to python 'example.ipynb' --stdout --template=my_custom_template.tplx。或者,您可以通过修改~.jupyter 目录中的jupyter_notebook_config.py 文件,通过菜单指定在导出为 Latex 时使用的默认模板。如果此文件不存在,您可以通过从命令行运行命令jupyter notebook --generate-config 来生成它。我的模板也位于~/.jupyter 目录中,因此我在jupyter_notebook_config.py 中添加了以下内容:

    # Insert this at the top of the file to allow you to reference
    # a template in the ~.jupyter directory
    import os.path
    import sys
    sys.path.insert(0, os.path.expanduser("~") + '/.jupyter')
    # Insert this at the bottom of the file:
    c.LatexExporter.template_file = 'my_template' # no .tplx extension here
    c.LatexExporter.template_path = ['.', os.path.expanduser("~") + '/.jupyter'] # nbconvert will look in ~/.jupyter
    

    要了解模板的工作原理,请先查看null.tplx((*- for cell in nb.cells -*)) 行遍历笔记本中的所有单元格。后面的if 语句检查每个单元格的类型并调用相应的块。

    其他模板扩展null.tplx。每个模板定义(或重新定义)一些块。层次结构是null->display_priority->document_contents->base->style_*->article

    您的自定义模板可能应该扩展 article.tplx 并将一些 Latex 命令添加到以您想要的方式设置表格的标题中。查看this blog post 以获取设置自定义模板的示例。

    【讨论】:

    • 太棒了!我应该将模板留在哪里?模板、tex文件的格式是什么?有样品吗? @butterwagon
    【解决方案2】:

    是否有任何设置可以更改表格大小以适应页面宽度? Latex 代码是这样的:\resizebox*{\textwidth}{!}{%

    【讨论】:

    • 我也有同样的问题,我就这个问题开了一个新问题link