LoginSignup
33
29

More than 5 years have passed since last update.

数式・画像付きのmarkdownをhtmlに変換

Last updated at Posted at 2015-02-15

数式や画像の入った文書をmarkdownで作って誰かと共有するときの方法です。
単一のhtmlファイルに変換して、Dropboxなどで共有する用途で使っています。

手順

原稿の準備

pandoc でmarkdownを変換します。

画像を入れるときは以下のように書きます。markdownファイルからの相対パスで指定できます。

![altの文字列](./fig.png)

数式は $f(x)$ というように一つの\$で囲うとインライン表示で数式を表示できます。
単一の行にしたい場合は\$\$で囲います。

$$f(x) = ax^2 + bx + c$$

変換

pandocでhtmlに変換するときにはいくつかオプションがありますが、とりあえず以下のコマンドに落ち着きました。

pandoc --self-contained -s --mathml mydoc.md -o mydoc.html

注意点

  • --self-contained を指定すると画像ファイルも含めた単一のhtmlファイルが作られます。
  • 数式を変換するには --mathml, --mathjax などのオプションを指定する必要があります。しかし self-contained と mathjax は pandoc 1.13ではバグのため共存できませんでした。そこでmathmlのオプションを使うようにしています。
  • 数式はchormeでは正しく表示できないようなのでfirefoxかsafariで表示します。

作られたファイルはdropboxなどで簡単に共有することができます。

(追記) Chromeでも数式を適用する方法

上で述べたようにmathmlを使うとchromeでは数式が適切にレンダリングされません。
--self-containedオプションと-mathjaxオプションを共存させるためのハックが上記のissueで表示されていました。
https://github.com/jgm/pandoc/issues/682#issuecomment-56773350
このコメントに含まれるJSをファイル(dynoload.jsという名前にしましょう)に保存して下記のコマンドで実行します。

pandoc --self-contained -s --mathjax=./dynoload.js mydoc.md -o mydoc.html

上記のファイルのgistを作りました。

pandoc --self-contained -s --mathjax=https://gist.githubusercontent.com/yohm/0c8ed72b6f18948a2fd3/raw/624defc8ffebb0934ab459854b7b3efc563f6efb/dynoload.js mydoc.md -o mydoc.html

でも大丈夫です。

(追記)github風のスタイルを適用する

さらに Pandocでgithub風CSSを使ったstandaloneなhtmlを生成 を参考にgithub風のスタイルを適用しましょう。

pandoc --self-contained -s --mathjax=https://gist.githubusercontent.com/yohm/0c8ed72b6f18948a2fd3/raw/624defc8ffebb0934ab459854b7b3efc563f6efb/dynoload.js -c https://gist.githubusercontent.com/griffin-stewie/9755783/raw/13cf5c04803102d90d2457a39c3a849a2d2cc04b/github.css mydoc.md -o mydoc.html

コマンドが長すぎるので、先ほどの記事を参考に.zshrcに以下のように記載しました。

~/.zshrc
pandoc_embed_html () {
  pandoc --self-contained -s --mathjax=https://gist.githubusercontent.com/yohm/0c8ed72b6f18948a2fd3/raw/624defc8ffebb0934ab459854b7b3efc563f6efb/dynoload.js -c https://gist.githubusercontent.com/griffin-ste    wie/9755783/raw/13cf5c04803102d90d2457a39c3a849a2d2cc04b/github.css $@
}

以後、 pandoc_embed_html mydoc.md -o mydoc.html で変換できます。

33
29
2

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
33
29