目录
基于Jupyter Notebook 版本: 7.2.2
Python环境:Anaconda安装,Win11 x64
操作记录日期:2024年11月
转PDF的两种方式
Notebook(.ipynb文件)转PDF常用的两种方式:
File --> save and Export Notebook as... --> Webpdf
- 即将web页面展现的notebook文件“打印”为PDF文件,较好保留Notebook原始风貌——所见即所得;
- 对应命令提示符指令:
jupyter nbconvert --to webpdf "C:\Users\nyjin\Python2024H2\Jupyter转PDF的安装和设置.ipynb"
- 若提示工具未安装,可用如下pip指令安装:
pip install nbconvert[webpdf] -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install playwright -i https://pypi.tuna.tsinghua.edu.cn/simple
File --> save and Export Notebook as... --> PDF
- 这种方法实际上是先将notebook转为latex文件(.tex),再调用pandoc和XeLatex工具将latex文件转为pdf文件。生成的PDF貌似更美观,且可根据多级标题自动生成目录。
- 对应命令提示符指令:
jupyter nbconvert --to pdf "C:\Users\nyjin\Python2024H2\Jupyter转PDF的安装和设置.ipynb"
第1中方式比较简单,本文就第2种方式的尝试进行记录。
pandoc安装
通过conda指令安装pandoc:
conda install -c conda-forge pandoc
>
安装完毕后检查pandoc版本:
pandoc --version
MiKTeX安装
官网下载最新版本并安装
检查xelatex版本
xelatex --version
设置latex文档模板
修改支持中文:block docclass
D:\anaconda3\share\jupyter\nbconvert\templates\latex\index.tex.j2
原始模板
((=- Default to the notebook output style -=))
((*- if not cell_style is defined -*))
((* set cell_style = 'style_jupyter.tex.j2' *))
((*- endif -*))
((=- Inherit from the specified cell style. -=))
((* extends cell_style *))
%===============================================================================
% Latex Article
%===============================================================================
((*- block docclass -*))
\documentclass[11pt]{article}
((*- endblock docclass -*))
修改后
((=- Default to the notebook output style -=))
((*- if not cell_style is defined -*))
((* set cell_style = 'style_jupyter.tex.j2' *))
((*- endif -*))
((=- Inherit from the specified cell style. -=))
((* extends cell_style *))
%===============================================================================
% Latex Article
%===============================================================================
((*- block docclass -*))
\documentclass[11pt]{ctexart}
((*- endblock docclass -*))
阻止对section添加自动编号:packages
D:\anaconda3\share\jupyter\nbconvert\templates\latex\base.tex.j2
注:可随时修改以更新自动编号策略
添加代码
如下两行代码:
\usepackage{titlesec}
\setcounter{secnumdepth}{0} % % Disable section numbering
在base.tex.j2
的block packages
内部
((*- block header -*))
---snip---
((* block packages *))
---snip---
\usepackage{titlesec}
\setcounter{secnumdepth}{0} % % Disable section numbering
((* endblock packages *))
指令
-
jupyter nbconvert --to pdf "C:\Users\nyjin\Python2024H2\第02课.ipynb"
-
jupyter nbconvert --to pdf "C:\Users\nyjin\Python2024H2\第06-07课.ipynb"
-
jupyter nbconvert --to pdf "C:\Users\nyjin\Python2024H2\Jupyter转PDF的安装和设置.ipynb"
存在问题
- Notebook中的Markdown单元中存在插入的图片时,转换失败!
- 无论是截图粘贴插入(attachment),还是独立图片文件插入,都不行。暂时无解(2024-11-6)
from IPython.display import Image
插图可行,但作为文档排版比较难看。。。