Develop with pleasure!

福岡でCloudとかBlockchainとか。

Play 2.0 PDF moduleで日本語出力

PlayFramework 2.0でPDFを出力する場合、joergviola/play20-pdf · GitHubというモジュールが公開されてる。

Controllerのアクションメソッドの最後に

PDF.ok(views.html.hoge).getWrappedResult

と書けば、scalaで記述したテンプレートファイルの内容がPDFとして出力される。

で、このテンプレートファイル内で日本語を扱いたい場合は↓のようにCSSの@font-faceで使用するフォントの定義する必要がある。

<html>
  <head>
    <style>
        @@font-face{
          font-family: "IPAGothic";
          src: url("/fonts/ipag.ttf");
          -fs-pdf-font-embed: embed;
          -fs-pdf-font-encoding: Identity-H;
        }
        body{
          font-family: "IPAGothic";
        }
    </style>
  </head>
  <body>
    ほげほげ
  </body>
</html>

↑ではipag.ttfというIPAフォントを指定しているけど、このフォントファイル自体は、Playのディレクトリ構成でconf/fonts/ipag.ttf に配置してる。
ちなみに、-fs-pdf-font-embedと-fs-pdf-font-encodingはPDFモジュールが内部で使ってるflying-saucer - XML/XHTML and CSS 2.1 renderer in pure Java - Google Project Hostingの拡張CSSらしい。