Joerg Viola

Lean. Web. Development.

A PDF Module for Play 2.0 Java

Yup! I just created my first Play 2.0 module! A lot of thanks to Steve for his tips for creating a module and publishing it on github pages.

So finally here is a preliminary release of my PDF module. It helps in generating PDF documents dynamically. You simply create standard Play 2.0 html templates and render them as HTML.

As an example, see this template:

document.scala.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@(message: String)

@main("Welcome to Play 2.0") {
    Image: <img src="/public/images/favicon.png"/><br/>
    Hello world! <br/>
    @message <br/>
  <table border="1">
      <tr>
          <td>1</td>
          <td>2</td>
      </tr>
      <tr>
          <td>3</td>
          <td>4</td>
      </tr>
  </table>
}

As you can see, it follows some simple rules:

  • use XHTML
  • specify external links as filepathes into the classpath of your application.

Then this template can simply be rendered as:

1
2
3
public static Result document() {
  return PDF.ok(document.render("Your new application is ready."));
}

where PDF.ok is a simple shorthand notation for:

1
ok(PDF.toBytes(document.render("Your new application is ready."))).as("application/pdf")

In order to use that module, simply add to your Build.scala these lines:

1
2
3
4
5
6
7
8
val appDependencies = Seq(
  "pdf" % "pdf_2.9.1" % "0.2",
  ...
)
val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA, settings = s).settings(
      resolvers += Resolver.url("My GitHub Play Repository", url("http://www.joergviola.de/releases/"))(Resolver.ivyStylePatterns),
      ...
)

…and the Source is with You!

I am just starting to use this module, so I don’t know how limited XHTML and CSS usage is. Just let me know in the comments - thanks!

Comments