By john on Mar 17, 2009
I recently ported a medium-sized Java web application to Ruby on Rails. Overall it was a gratifying experience but I struggled with PDF generation, and specifically the limits of the Ruby PDF generator PDF::Writer and associated SimpleTable.
Actually PDF::Writer itself is fairly powerful but unfortunately SimpleTable lives up to its name by lacking many of the features found in other PDF generators.
My original Java app uses the awesome iText PDF generator which has extensive table support.
After fiddling with SimpleTable for a while, I gave up and wrote a simple bridge between my Rails app and my original Java PDF generation servlet. On the rails side I create a delimited string containing each record to be printed, and post that to the servlet with:
On the Java side I parse the InputStream to retrieve the values, and generate table cells using the iText APIs.
This is straightforward, but it bugs me having to maintain two codebases in two languages, and deploy two separate applications, one in an app server, to support PDF generation. It would be far preferable to access iText directly from Ruby.
So I installed JRuby on my S10 box, and entered these two commands (courtesy Charles Nutter):
% gem install glassfish-gem-10.0-SNAPSHOT.gem % glassfish_rails myapp
And voila: my app is running inside Glassfish on JRuby. Wow - that was easy! I can get rid of my mongrels and manage everything from GlassFish. Even better, I can now call Java from within ruby:
setenv CLASSPATH itext.jar require 'java' include_class 'java.io.FileOutputStream' include_class 'com.lowagie.text.Document' document = Document.new(PageSize::A4.rotate(), 10, 10, 10, 10) pdfFile = FileOutputStream.new("it_works.pdf") writer = PdfWriter.getInstance(document, pdfFile) table = PdfPTable.new(9)
This is the best of all worlds. Of course there are some downsides with this approach, such as inevitable impedance mismatches between Java and Ruby, code maintainability issues, etc. but this approach quickly and elegantly solved my original problem of not being able to access iText.
First impressions: JRuby Rocks.