Using JRuby with PDF Java Toolkit

Using JRuby with PDF Java Toolkit

It’s traditional when learning a new programming language, to start off with a ‘Hello World’ program. Or at least, that’s how the tutorial generally starts off. The new programming language in this case is Ruby, or more specifically, JRuby which is Ruby implemented to run within the Java Virtual Machine.

The appeal of JRuby over regular Ruby is that I should be able to use Datalogics PDF Java Toolkit (PDFJT) in a JRuby program. I could, of course, use Java with PDFJT, but why not mix things up a bit? So, as a proof-of-concept, I ported PDFJT’s HelloWorld.Java to JRuby.

The first step, is to declare we require ‘java’:

After which, we will require PDFJT itself, and Talkeetna:

And those have their own requirements, which are usually taken care of behind the scenes by Maven, so I pulled out the jar I needed from my maven cache:

Since this is a proof-of-concept rather production code, for the sake of expediency, we’ll ignore the questionable hard-coded paths.

Next we’ll do some java-style imports:

In case it’s not already obvious by now, we are going to be opening a (new) PDF Document and laying out a paragraph. If you consider a two-word sentence to be a paragraph, that is.

But before that, we need the obligatory setting of the license path for the LicenseManager. Here is where things start to get interesting.

First, all of the periods in the fully-qualified path to the LicenseManager class have been removed in favor of some weird camel-casing. Second, LicenseManager’s setLicensePath method has turned into a license_path property.

And the next line:

Oh look, we didn’t declare that pdf_doc variable’s type. Wait, isn’t PDFOpenOptions.newInstance a method? Where are its parentheses?

Let’s do that again. Let’s pass in pdf_doc as a parameter to the LayoutEngine constructor!


No parentheses:

And more JRuby magic with java methods becoming properties:

So, let’s wrap things up.

Here’s what we just did: we created a new PDF Document, created a new LayoutEngine for that document, created a list of font(names)s, and a new paragraph. We then modified the paragraph’s style to use the list of fonts, added the paragraph to the layout engine, generated the PDF content by closing the LayoutEngine, and saved the document to a new file called HelloWorld.pdf.

There’s just one last bit to the program:

We ensure that the pdf_doc would be closed if an exception were to interrupt the creation of this document. A formality in this case, but it becomes more important when you are opening and manipulating documents from all corners of the earth.

After all that, call jruby HelloWorld.rb from the command-line to run it.

This is just barely dipping our toes into the possibilities of PDFJT being used with JRuby, but so far, things look promising. If you have any questions, comment below or reach out to us.

Leave a Reply

Your email address will not be published.