如何修改nbconvert WebPDFExporter生成PDF的页面尺寸?
解决WebPDFExporter自定义模板样式不生效及表格超出页面问题
问题根源分析
你遇到的模板样式不生效问题,核心原因有两个:
- 模板语法错误:
extra_css块中混入了<p>标签,这个块的作用是注入纯CSS内容,HTML元素会破坏页面结构,导致后续CSS规则无法被浏览器正确解析。 - WebPDFExporter的渲染逻辑:它依赖Chrome将HTML转为PDF,部分CSS规则(如
@page)可能被Chrome的默认PDF渲染设置或nbconvert的默认样式覆盖;同时表格超出宽度需要额外的自适应样式处理。
修复步骤
1. 修正自定义模板
修改widepdf/index.pdf.j2,移除extra_css块中的HTML元素,只保留CSS规则:
{%- extends 'webpdf/index.pdf.j2' -%} {% block body %} <p>Extra body</p> {{ super() }} {% endblock body %} {% block extra_css %} {{ super() }} <style type="text/css"> body { background-color: red !important; } p { border: 1px solid red !important; } /* 设置宽幅页面尺寸,同时调整边距避免内容裁切 */ @page { size: 14in 60in; margin: 0.5in; } /* 处理表格超出问题:让表格自动换行或适应页面宽度 */ table { width: 100% !important; table-layout: fixed !important; } table td, table th { word-wrap: break-word !important; white-space: normal !important; } </style> {% endblock extra_css %}
2. 调整WebPDFExporter配置
Chrome的PDF渲染可能会忽略@page规则,此时可以通过chrome_options直接传入浏览器命令行参数强制设置页面尺寸:
修改你的Python代码,添加Chrome选项配置:
notebook_node = nbformat.read(notebook_output_path, as_version=4) conf = Config() # 原有配置保持不变 conf.WebPDFExporter.allow_chromium_download = True conf.WebPDFExporter.disable_sandbox = True conf.WebPDFExporter.paginate = True # 启用分页,配合@page规则生效 # 添加Chrome命令行参数,强制设置页面尺寸 conf.WebPDFExporter.chrome_options = [ '--no-sandbox', '--disable-dev-shm-usage', '--print-to-pdf-page-size=14in,60in' # 直接指定PDF页面尺寸 ] # 仅显示输出内容相关配置 conf.TemplateExporter.exclude_input = True conf.TemplateExporter.exclude_input_prompt = True conf.TemplateExporter.exclude_output_prompt = True # 模板路径配置 conf.TemplateExporter.extra_template_basedirs = str(_TEMPLATES_DIR) conf.TemplateExporter.template_name = "widepdf" pdf_exporter = WebPDFExporter(config=conf) pdf_data, unused_resources = pdf_exporter.from_notebook_node(notebook_node) with open(pdf_path, "wb") as pdf_file: pdf_file.write(pdf_data)
3. 验证模板生效
修改后重新生成PDF,你会看到:
- 页面背景变红、段落带红色边框(验证基础样式生效)
- 页面尺寸变为14英寸宽(解决宽表格空间问题)
- 表格内容自动换行,不再超出页面边界
关键注意事项
extra_css块必须只包含CSS内容,任何HTML元素都会导致样式解析失败- Chrome的
--print-to-pdf-page-size参数优先级高于CSS的@page规则,当两者冲突时以命令行参数为准 - 表格的自适应样式需要结合
table-layout: fixed和word-wrap,确保长内容能在单元格内换行
内容的提问来源于stack exchange,提问作者markfickett
相关产品推荐
相关产品推荐

