Nbconvert导出HTML/PDF时如何修改代码单元格输出字体为Arial
问题说明
使用nbconvert将Jupyter Notebook转换为HTML/PDF格式时,配置自定义模板后Markdown文本已经正常显示为Arial字体,但代码单元格中print语句输出的文本字体无法统一,例如print("This is my code")的输出字体和正文不一致,需要将全文字体统一设置为Arial。
当前使用的index.html.j2自定义模板内容如下:
{%- extends 'lab/index.html.j2' -%} {%- block html_head_css -%} {{ super() }} <style> @font-face { font-family: Arial, Helvetica, sans-serif; font-style: normal; font-weight: 400; } h1, h2, h3 { font-family: Arial, Helvetica, sans-serif; } .header { overflow: hidden; # background-color: #f1f1f1; # padding: 20px 10px; } .logo-container { # margin: auto; # width: fit-content; text-align:left; width:50px; } body { font-family: Arial, Helvetica, sans-serif; } </style> {%- endblock html_head_css -%} {% block body_header %} <body class="jp-Notebook theme-light" style="padding: 0; margin: 0;"> <div class="header"> <div class="logo-container width:50px;"> <img src="myimage.png"> </div> </div> <div style="padding: 20px; margin: 20px;"> {% endblock body_header %} {% block body_footer %} </div> </body> {% endblock body_footer %}
效果参考(上方为Markdown单元格内容,下方为print语句输出内容):
解决方法
代码输出区域字体不生效,是因为nbconvert默认给代码输入、输出块的pre标签、对应Jupyter组件类单独设置了等宽字体,这类选择器的优先级高于你给body设置的全局字体规则,因此样式没有被覆盖。
直接在现有<style>标签内追加以下CSS规则,即可强制将代码输入、输出区域的字体统一为Arial:
/* 覆盖代码区域默认等宽字体配置 */ .jp-CodeCell, .jp-InputArea pre, .jp-OutputArea .output_text, .jp-OutputArea pre, pre { font-family: Arial, Helvetica, sans-serif !important; }
规则中添加!important是为了保证样式优先级足够高,不会被nbconvert自带的默认样式覆盖。如果导出PDF时仍存在字体不一致的问题,先确认执行导出操作的系统中已安装Arial字体,避免渲染时自动fallback到其他系统自带字体。
内容的提问来源于stack exchange,提问作者user2154589
相关产品推荐
相关产品推荐

