So I needed to get PDF templating working within Ruby i.e merging data from our DB with PDF templates that were built by others. My first attempts were using prawn the fav ruby PDF toolkit. but this does not allow you to take as input a template PDF and spit out populated PDF.

So I moved to iText and this was great – worked beautifully but how to call it from ruby. Enter rjb. So installing it had some problems on Linux

1. gem install rjb always gave me this error
extconf.rb:48: JAVA_HOME is not set. (RuntimeError)

  • This even though my JAVA_HOME was set in my .bashrc. This can be fixed by the running as follows (note trailing / in JAVA_HOME) – just run the command exactly as – setting JAVA_HOME anywhere else wont work

sudo JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun/ gem install rjb

2. Once installed I could play around with it inside the ruby console – but running it within rails I always got a Segmentation Error

  • This link gave me some clues . So I removed the gem and reset the javac and the java to point to the same jdk – but no joy.
  • Then I moved back from jdk6 to jdk5 and voila everything works

I added the following to my config/environment.rb so that I could access PDFGenerator (my custom java class using iText api) within my rails controller

require “rjb”

Rjb::load(“#{RAILS_ROOT}/script/PDFGenerator/iText-5.0.3.jar:#{RAILS_ROOT}/script/PDFGenerator/:#{RAILS_ROOT}/script/PDFGenerator/groovy-all-1.7.4.jar”,[‘-Xms64m’, ‘-Xmx512m’])

PDF_GEN_CLASS = Rjb::import(‘PDFGenerator’)
PDF_GEN = PDF_GEN_CLASS.new

Then in my controller I can access the instance of my custom class as follows

PDF_GEN.convert(…..)

This allows for a single instance of the class to be reused – of course you have to ensure that the class is stateless as it will be reused in every call.