Convert Jupyter Notebook with CJK to PDF on MacOS

Install Dependencies

Follow nbconvert Installation Guide to install dependencies.

1
2
3
pip install nbconvert
pip install pandoc
brew install mactex

Install CJK Font

Use system font or install any CJK font. I recommend Sarasa Gothic (更纱黑体 / 更紗黑體 / 更紗ゴシック / 사라사고딕).

1
brew install font-sarasa-gothic

Convert the Notebook to PDF

  1. Convert the notebook to tex

    1
    
    jupyter nbconvert --to latex notebook-to-convert.ipynb
    
  2. Modify the tex file to add CJK package and set CJK font

    Insert the 2nd and 3rd lines below into notebook-to-convert.tex. Make sure the font is available in system.

    1
    2
    3
    4
    5
    
    \documentclass[11pt]{article}
        \usepackage[slantfont, boldfont]{xeCJK}
        \setCJKmainfont{Sarasa UI SC}
        \usepackage[breakable]{tcolorbox}
        \usepackage{parskip} % Stop auto-indenting (to mimic markdown behaviour)
    
  3. Convert tex to pdf

    1
    
    xelatex notebook-to-convert.tex
    

Shell Script Helper

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/bin/zsh

FILE="notebook-to-convert"

# Generate Tex
jupyter nbconvert --to latex $FILE.ipynb

# Enable CJK
# Note: sed MacOS syntax
sed -i '' '2i\
    \\usepackage[slantfont, boldfont]{xeCJK}\
    \\setCJKmainfont{Sarasa UI SC}' $FILE.tex

# Generate PDF
xelatex $FILE.tex