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

如何用nbconvert在Jupyter Notebook的Markdown单元格实现精准换行生成PDF

解决方案

问题根源是你用的<br>标签在nbconvert通过LaTeX渲染PDF时不会被正确解析,导致内容挤在一起。批量生成场景下,可通过以下方法解决:

方法1:使用Markdown原生格式(推荐)

放弃<br>,改用Markdown的换行和缩进/列表规则,让nbconvert自动识别格式:

  • 主标题后空一行,给每个B1、B2项添加4个空格缩进:
    B) How far do you agree or disagree with the following statements? (Strongly Disagree to Strongly Agree, 1 to 5)
    
        B1. The software used in this course are easy to learn and we got familiar with them fast
        B2. We have enough technical support to adapt to the usage of the software
    
  • 或者用无序列表实现更规范的缩进:
    B) How far do you agree or disagree with the following statements? (Strongly Disagree to Strongly Agree, 1 to 5)
    
    -   B1. The software used in this course are easy to learn and we got familiar with them fast
    -   B2. We have enough technical support to adapt to the usage of the software
    

方法2:嵌入LaTeX换行与缩进命令

利用nbconvert依赖LaTeX渲染的特性,直接在内容中使用LaTeX语法:
在Python生成内容时(注意转义字符):

content = """B) How far do you agree or disagree with the following statements? (Strongly Disagree to Strongly Agree, 1 to 5)\\
\\quad B1. The software used in this course are easy to learn and we got familiar with them fast\\
\\quad B2. We have enough technical support to adapt to the usage of the software"""

其中\\是LaTeX的换行命令,\\quad是标准缩进命令,比手动空格更稳定。

方法3:自定义LaTeX模板(进阶)

若需大量格式定制,可修改nbconvert的LaTeX模板,添加<br>标签的解析规则(比如替换为LaTeX换行符),然后在转换命令中指定模板:

!jupyter nbconvert --to pdf --no-input --PDFExporter.latex_count=1 --PDFExporter.dpi=500 --template=custom_template.tplx """ + sheet_name + """.ipynb

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:40:28