pandocでドキュメントを書いているときにUMLで図を差し込みたいことがある。
UMLを描くためにはいろいろとツールがあるが、テキストから図を生成できるPlantUMLが便利。
PlantUML自体は以前取り上げたことがあるので、導入方法はこちらで。
pandocではフィルタを使えば、plantumlの記法で記述したコードブロックを直接、図に変換することができる。
いろいろと実装が存在するが、今回はここのものを使用する。
ダウンロード
パスが通っている場所にフィルタのスクリプトをダウンロードする。
ここでは~/bin
とする。
$ cd ~/bin $ wget https://raw.githubusercontent.com/matthiasbeyer/pandoc-paper-template/master/scripts/plantuml-filter.py $ chmod +x ./plantuml-filter.py
スクリプトの作成
このフィルタはパスが通っているところにplantuml
という名前でPlantUMLが実行できることを想定しているため、ラッパーとなるスクリプトを~/bin/plantuml
として作成する。
#!/bin/bash java -jar plantuml.jar $@
これに実行権限をつける。
$ chmod +x ~/bin/plantuml
図の埋め込み
pandocのマークダウンに次のように記述する。
```{.plantuml}
start
:test;
stop
```
これを試しにtest.md
として保存する。
変換
これを次のように変換する。
pandoc -F plantuml-filter.py -otest.html test.md
次のような図が生成される。
日本語対応
PlantUMLのコードブロックに日本語が含まれる場合エラーが発生するので、次のように修正した。
--- plantuml-filter.py~ 2016-12-09 01:14:35.235721804 +0900 +++ plantuml-filter.py 2016-12-09 01:39:31.432327258 +0900 @@ -12,7 +12,7 @@ from pandocfilters import toJSONFilter, Str, Para, Image, attributes def sha1(x): - return hashlib.sha1(x).hexdigest() + return hashlib.sha1(x.encode('utf-8')).hexdigest() def out(s): sys.stderr.write('\t[PLTUML] ' + s + '\n'); @@ -21,7 +21,7 @@ def pipe(cmd, data): p = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) - p.stdin.write(data) + p.stdin.write(data.encode('utf-8')) p.stdin.close() data = p.stdout.read() p.stdout.close()
次のようなコードブロックを変換する。
```{.plantuml}
start
:日本語;
stop
```
すると、次のような図が生成される。