12
7

More than 3 years have passed since last update.

JupyterのPDF出力の日本語対応法(2020年12月版)

Last updated at Posted at 2020-12-24

2年以上も前に日本語のJupyter NotebookをPDFとしてダウンロードするという記事を書きましたが、その後nbconvertなどの仕様変更があり、役に立たなくなっていたようです。
そこで、改訂版を記しておきます。

TeXのインストール

Ubuntuの場合

下記のモジュールをインストールすれば良いようです。

sudo apt install texlive-lang-japanese
sudo apt install texlive-xetex
sudo apt install pandoc

Macの場合

MacTexをインストールするのがもっとも簡単と思います。
なお、私の場合にはMacPortsを使っていたので、ghostscriptはMacPortsでインストールしたものを使いました。

テンプレートファイルの変更

nbconvertに付属するテンプレートでは日本語の文字が表示されないので、修正が必要です。

テンプレートファイルの配置先

テンプレートファイルは以前はnbconvertのインストールディレクトリにありましたが、現在は環境によって配置されるディレクトリが変わるようです。jupyter --pathコマンドを実行すると、jupyterがデータファイルを検索するディレクトリ一覧が表示されるので、これらの場所を探してみると良いでしょう。

# jupiter --path の実行例
$ jupyter --path
config:
    /home/basicuser/.jupyter
    /usr/local/etc/jupyter
    /etc/jupyter
data:
    /home/basicuser/.local/share/jupyter
    /usr/local/share/jupyter
    /usr/share/jupyter
runtime:
    /home/basicuser/.local/share/jupyter/runtime

上記のdata:以下に列挙されているディレクトリのいずれかが配置先です。
この例では、
/home/basicuser/.local/share/jupyter/nbconvert/templates/latex
にTeXのテンプレートファイル(拡張子.tex.j2)が配置されていました。

変更内容

テンプレートファイルindex.tex.j2ファイルの内容を、

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 -*))

から、下記のように変更します。

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[xelatex,ja=standard]{bxjsarticle}
((*- endblock docclass -*))

注意すること

なお、venvなどの仮想環境の場合には、テンプレートファイルのインストール先も仮想環境ごとに異なります。例えばvenvの場合、
venv/share/jupyter/nbconvert/templates/latex
に配置されていました。

また、テンプレートファイルの場所は、jupyter_nbconvert_config.jsonで指定可能です。上記のjupyter --pathconfig:でリストアップされたディレクトリにこのファイルが生成されている場合があるようです。標準的な場所に見つからない場合には、このファイルがないかどうかを確認してみてください。

参考にしたサイト

Jupyter Notebook をPDFで保存する方法(日本語対応)

12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7