Mike Steele sent me an email in reference to an article I wrote for the ColdFusion Developer’s Journal a year or so ago. In the email, he mentions that he is trying to use the iText Java-PDF library with ColdFusion MX:
… The getInstance method is static and according to your July 2003 CFDJ article, you can’t instantiate an object in CF this way.
In the article I said this:
… using the CreateObject() function does not get you access to an instance of an object. In order to access a Java object, you must either a) first call the CreateObject() method and then the init() method, which in the above example, maps to the default constructor in Java, or b) call any nonstatic method on the object, which causes ColdFusion to then instantiate the object for you.
I guess this statement needs to be amended to include a third possible, but not always valid solution: call a static method on the class which returns an instance of the object in question. In this case the API designer included a static method ‘getInstance()’ on the PDFWriter class. Given that news, you can take the quick example that the author of the iText library gives here to create a PDF in a snap using ColdFusion:
// create a 'Document' object
document = CreateObject("java", "com.lowagie.text.Document");
// get an outputstream for the PDF Writer
fileIO = CreateObject("java", "java.io.FileOutputStream");
// call the constructor, pass the location where you want
// the pdf to be created
// get a PDF Writer var
writer = CreateObject("java", "com.lowagie.text.pdf.PdfWriter");
// call the static 'getInstance' factory method
// open the document
// create a new paragraph
paragraph = CreateObject("java", "com.lowagie.text.Paragraph");
// add the paragraph
// close the document (PDF Writer is listening and will automatically
// create the PDF for us
Copy that code into a cfml page and make sure you’ve downloaded the iText jar to the /lib/ directory of your ColdFusion server and you should be able to create PDF’s in a jiffy!
Full source code available here.