LoginSignup
1
2

More than 5 years have passed since last update.

Play Framework 2.6.x Scala PDF

Last updated at Posted at 2017-10-10

Play Framework 2.6.x / Scala で PDF出力する方法

GitHub にあるオープンソースのライブラリを使う。
https://github.com/benjohnde/play-pdf

mavenでは公開されていないので
ローカルでjarライブラリをビルドする。

cd module
sbt clean
activator publish-local

module/target/scala-2.12pdf_2.12-1.1.3.jar が生成されるので、この jar を導入先プロジェクトの lib ディレクトリにコピーする。(libディレクトリがない場合は新規作成する)

build.stb に下記を追記する。

build.stb
libraryDependencies ++ Seq(
    "de.benjohn.play" %% "pdf" % "1.1.3"
)

日本語フォントを使う場合は、conf ディレクトリの下に fonts ディレクトリを作成して、フォントファイル(例 ipag.ttf)をコピーする。

conf
  +- fonts
       +-- ipag.ttf

読み込むフォントファイル名を application.conf に追記する。

application.conf

pdf.fonts = ["fonts/ipag.ttf"]

PDFのテンプレートとなるHTML

views/main.scale.html

<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>@title</title>
        <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>
        <h1>画面表示</h1>

コントローラー

def index = Action {
    Ok(PDF.toBytes(views.html.index("日本語 にほんご ニホンゴ JAPAN"))).as("application/pdf")
}

play-mailer でメールにPDFを添付する場合は PDF.toBytes で得られたバイト配列を AttachmentData する。(一時ファイルに保存する必要なし)

1
2
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
1
2