The Source for Java Technology Collaboration
User: Password:



Krishnan Viswanath

Krishnan Viswanath's Blog

Open Office Java API

Posted by tchangu on December 30, 2005 at 06:20 AM | Comments (15)

When I worked for a consulting firm I got an opportunity to work on a Strategy & Operations pursuit. The task was to fill up a 20 page MS Word report template with lots of data from MS Access and Oracle (which was backend to some ERP system). The requirement was to produce 10 or so reports quickly, which showed the client how the firm can help them to define a strategic sourcing model followed by a transformation roadmap.

Not being a fluent VB Scripter, I was totally frustrated trying different things - manually plugging in data, patchy VB Scripting, Apache POI - but nothing worked satisfactorily. Finally after looking around, I ended up discovering OpenOffice UNO Java API (Universal Network Objects). After going through an initial ramp, it worked out pretty good. With OO UNO and JDBC, ugly and complex reporting became a breeze!

Open Office UNO API is pretty involved in concept and is complex as well. Of course it’s pretty powerful and can do much more than what I made use of. However, there is very little general documentation like articles etc available online. But Sun’s Developer's guide and supplied samples is very good. For starters here is some code that helped me going.

First - Read an existing document, and this can be accomplished by
// get the remote office component context
xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");

// Get the remote office service manager
XMultiComponentFactory xMCF = xContext.getServiceManager();

// Get the root frame (i.e. desktop) of openoffice framework.
Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);

// Desktop has 3 interfaces. The XComponentLoader interface provides ability to load
// components.
XComponentLoader xCompLoader = (XComponentLoader)
		UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class, oDesktop);

// URL of the component to be loaded
String sUrl = "file:///[file name]";

// Load the document, which will be displayed. More param info in apidoc
XComponent xComp = xCompLoader.loadComponentFromURL(sUrl, "_blank", 0, new PropertyValue[0]);

// Get the textdocument
XTextDocument aTextDocument = (XTextDocument)UnoRuntime.queryInterface(
                  com.sun.star.text.XTextDocument.class, xComp);

Now that we have text document we can manipulate in how ever manner we want. In my particular case, I had to deal with data that were in tables. This was accomplished by
// Query the XTextTablesSupplier interface from our document
XTextTablesSupplier xTablesSupplier = (XTextTablesSupplier) UnoRuntime.queryInterface(
                 XTextTablesSupplier.class, aTextDocument );

// Get the tables collection
XNameAccess xNamedTables = xTablesSupplier.getTextTables();

// Query the XIndexAccess from the tables collection
XIndexAccess xIndexedTables = (XIndexAccess) UnoRuntime.queryInterface(
                 XIndexAccess.class, xNamedTables);

for (int i = 0; i < xIndexedTables.getCount(); i++) {
  Object table = xIndexedTables.getByIndex(i);
  XTextTable xTable = (XTextTable) UnoRuntime.queryInterface(
                  XTextTable.class, table);

  // Getting Table Rows
  XTableRows xRows = xTable.getRows();

  // Getting the right Table Cell (Hard Coded as B2).
   XText xCellText = (XText) UnoRuntime.queryInterface (
                  XText.class, xTable.getCellByName ( "B2" ) );

   // Make JDBC calls. Perform data tranformation and set it
   xCellText.setString("Hello Worlds");
}
The final task after all the transformation has been performed is to save the document.
// URL where the document is to be stored
String storeUrl = "file:///Test_97.rtf";

XStorable xStorable = (XStorable)UnoRuntime.queryInterface(XStorable.class, aTextDocument);
PropertyValue[] storeProps = new PropertyValue[1];
storeProps[0] = new PropertyValue();
storeProps[0].Name = "FilterName";
storeProps[0].Value = "Rich Text Format";

xStorable.storeAsURL(storeUrl, storeProps);
Of course the document could be sent to the printer as well. Here is the code to do that
XPrintable xPrintable = (XPrintable)UnoRuntime.queryInterface(XPrintable.class, aTextDocument);
PropertyValue[] printerDesc = new PropertyValue[1];
printerDesc[0] = new PropertyValue();
printerDesc[0].Name = "Name";
printerDesc[0].Value = "PDFCreator";
xPrintable.setPrinter(printerDesc);

PropertyValue[] printOpts = new PropertyValue[1];
printOpts[0] = new PropertyValue();
printOpts[0].Name = "Pages";
printOpts[0].Value = "1";
xPrintable.print(printOpts);
Enjoy!

Bookmark blog post: del.icio.us del.icio.us Digg Digg DZone DZone Furl Furl Reddit Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment

  • Very Interesting article. I've been itching to get into this API, but I haven't found a good excuse just yet (I would have to incorporate it into existing projects to make time for it).

    The article really does lack some good resource links though.

    I found this developers guide (although I haven't started reading it yet):

    http://api.openoffice.org/DevelopersGuide/DevelopersGuide.html

    Is that something you used? Do you have other/better/different resource(s) for somebody who would like to jump into this?

    I'd probably be looking for ways to build spreadsheets and suck data out of spreadsheets.

    Posted by: smbell on January 04, 2006 at 10:23 AM

  • Apparently I need to use html breaks

    rather than just hitting return.

    Posted by: smbell on January 04, 2006 at 10:25 AM

  • It's also worth noting that OO doesn't need to be installed on the local machine for this stuff to work, you can use it as a server - submit data and get a formatted document/report in return.

    Posted by: luano on January 04, 2006 at 10:32 AM

  • Yes there arent' very many resources out there. The best resource is the developer guide which tries to do two things at the same time - explain concepts, which could be difficult to follow and snippets from code example. Of course the samples are reasonably documented

    OO has robust support for spreadsheets too. I ran into limitation with Apache POI HSSF because it doesn't do spreadsheets with embedded images (not sure if that is still the case) But with OO I *think* you should be golden

    As luano pointed out, one could connect to a open office "server" running in a remote m/c too.

    In all this is a really good & powerful API but grossly under used :((

    Posted by: tchangu on January 04, 2006 at 04:01 PM

  • You just kicked open a door that i've been peeking through for a while now. I was too lazy to do the digging around all these days. Time to take a deep dive into UNO now. Thanks. :-)

    Posted by: bharathch on January 04, 2006 at 09:55 PM

  • Do you think it may be easy and worthful to use OOo to do some reporting like JasperReports [1] do ?


    [1] http://jasperreports.sf.net

    Posted by: rouc1 on January 12, 2006 at 01:13 PM

  • Jasper reports is actually really good. However my situation during the time was different and just didnt have enough time to do port MS Word report template into Jasper reports design in XML. So the best short cut as plug the required data into the word document itself. However if I were to design and develop a reporting solution with longer shelf life, then I would have certainly taken the path of jasper reports or other reporting engines.

    Posted by: tchangu on January 12, 2006 at 05:33 PM

  • Can u suggest me something ...how to create a pdf file using the openoffice.
    requirements : datasource will be an XML file and input will be a rtf template.

    I want to map the palceholders inside the rtf template and Want to replace those placeholders with their corresponding value from the XML file. and it will crfeate the PDF file with those data from the XML file.

    thanks in advance
    Utpal das

    Posted by: utpaldasin on February 02, 2006 at 04:02 AM

  • In my current project I have to convert word to xml. To do this in OO, Do we need to have the OO Server running?

    Posted by: anu_u on April 18, 2006 at 10:03 AM

  • Hi,
    I want to convert a word file in to an xml file using openoffice API for java. Is it possible?

    waiting or your reply.

    Regards,
    Niketu Dave

    Posted by: niketu on May 27, 2006 at 12:09 AM

  • I am trying to wite a java program that opens a writer document and exports it to html....

    XStorable xStorable = (XStorable)UnoRuntime.queryInterface(XStorable.class, xComp);
    PropertyValue[] storeProps = new PropertyValue[1];
    storeProps[0] = new PropertyValue();
    storeProps[0].Name = "FilterName";
    storeProps[0].Value = "HTML (StarWriter)";
    xStorable.storeToURL("C:\\test.html",storeProps);


    I have gone through all the sample code I could find, and I still get a com.sun.star.task.ErrorCodeIOException...
    i also want to save this code just as an Openoffice document ......it still gives the same exception ...
    xStorable.storeAsURL("C:\\test.odt",storeProps);

    plz help

    Posted by: priyankaoof on February 07, 2007 at 12:25 AM

  • Hi.I want to convert MS word (.doc)file in to pdf file format using Open Office .Can u please give me sample code for that.How to use office api for conversion .

    Posted by: amolpatil123 on April 20, 2007 at 01:19 AM

  • Is there a way to set the priority for the document during print process?

    Posted by: venkyrjy on June 19, 2007 at 05:51 PM

  • Hello,
    I m in need of converting a Word Document into Text file using Java?
    Can any body help regarding this?

    Posted by: jennythompson on August 02, 2007 at 12:16 AM

  • Hello

    My name is Mauricio, Could anybody help me? I need to connect to a soffice installation in a remote machine which is running under solaris 10. But I have no idea of how to do it.

    Please could someone help me?

    Thanks in advance

    Posted by: cargdrac on September 07, 2007 at 08:58 AM





Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds