如果需要将jupyter notebook转换为pdf,直接在浏览器或vscode中转换即可。
如果需要只保留代码运行结果、MarkDown块,需要借助nbconvert工具进行转换。
安装 nbconvert
直接
pip install nbconvert
要解锁其全部功能,还需要安装其他几个工具:
- pandoc:从 pandoc 下载pandoc并安装,如果是Windows可直接下载其中的pandoc-x.x.x-windows-x86_64.msi
- Tex:nbconvert使用 XeTex 渲染pdf,需要安装完整的 Tex环境。
转换命令
在命令行中使用nbconvert:
jupyter nbconvert --to pdf --no-input --TagRemovePreprocessor.remove_cell_tags 'remove-cell' ipynb_file_path
其中 --no-input
参数会排除所有的代码块,实现只保留代码运行结果和MarkDown块的效果。
--TagRemovePreprocessor.remove_cell_tags
可以移除MarkDown中带有指定标记的块,如果不需要可以不设置。
可能遇到的问题
如果 MarkDown 块中包含图片,直接转换为pdf可能报错:
! Undefined control sequence.
l.403 \pandocbounded
{\includegraphics[keepaspectratio]{book.png}}
?
! Emergency stop.
l.403
No pages of output.
Transcript written on notebook.log.
解决方法是先转换为latex:
jupyter nbconvert --to latex --no-input --TagRemovePreprocessor.remove_cell_tags 'remove-cell' ipynb_file_path
打开编译后的tex文件,把里面的
\pandocbounded{\includegraphics[keepaspectratio]{xxx.png}}
改为:
\includegraphics[keepaspectratio]{xxx.png}
注意其中图片的路径,然后用XeTex 手动编译。