HelloWord.rb:Using iText & JRuby

JRuby is the effort to recreate the Ruby interpreter in Java. JRuby is tightly integrated with Java to allow both to script any Java class and to embed the interpreter into any Java application.

and

iText is a library that allows you to generate PDF files on the fly.
The iText classes are very useful for people who need to generate read-only, platform independent documents containing text, lists, tables and images. The library is especially useful in combination with Java(TM) technology-based Servlets: The look and feel of HTML is browser dependent; with iText and PDF you can control exactly how your servlet’s output will look.

So how about Creating and Manipulating PDF by using iText & JRuby?
The following is a HelloWorld example ported from the iText tutorial-HelloWorld.java.

When I run it, I got the error:

"Hello World"
Document failed: com.lowagie.text.DocumentException: The document is not open ye
t; you can only add Meta information.HelloWorld.rb:33:in `close': com.lowagie.te
xt.ExceptionConverter: The document is not open. (NativeException)
from HelloWorld.rb:33
from :-1
Complete Java stackTrace
java.lang.RuntimeException: The document is not open.

at com.lowagie.text.pdf.PdfWriter.getDirectContent(PdfWriter.java:1499)
at com.lowagie.text.pdf.PdfDocument.newPage(PdfDocument.java:762)
at com.lowagie.text.pdf.PdfDocument.close(PdfDocument.java:947)
at com.lowagie.text.Document.close(Document.java:533)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.

That means document.open() does not work. what is the matter? I tried to debug this example in jirb, when wrote down document.open() and hit return, the result is false.
So I decide do some hack on iText, clone open method of Document but with a different method name”doOpen”.
and also replace “document.open()” with “document.doOpen()“,
jruby HelloWorld.rb, it work now.
I do not know why, but will try to find it.

P.S.
the iText I used is v1.4.5, jRuby is 0.9.0
the usage is:
d:>set CLASSPATH=%CP%;%CLASSPATH%;itext-1.4.5.jar
d:>jruby HelloWorld.rb

Leave a Reply