Sunday, March 13, 2011

Your first OpenOffice3 SDK Java application

Environment setup

Download OpenOffice 3 here

You will need to add the following jar files to your classpath:

(openoffice.org/ure/share/java)
(on my ubuntu linux: /usr/lib/openoffice/basis3.2/ure-link/share/java/)
  • ridl.jar
  • jurt.jar
  • juh.jar
(openoffice.org/basis3.2/program/classes)
(on my ubuntu linux: /usr/lib/openoffice/basis3.2/program/classes)
  • unoil.jar

You also need add openoffice program (/opt/openoffice.org3/program) to you classpath (on my ubuntu linux: /usr/lib/openoffice)

Here how looks my project setup in eclipse:


Code
And here is code:
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.io.IOException;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.text.XText;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

public class Program {

 public static void main(String[] args){
  XComponentContext xContext = null;

  try {
   xContext = Bootstrap.bootstrap();
  } catch (BootstrapException e) {
   e.printStackTrace();
  }

  XMultiComponentFactory xMultiComponentFactory = null; 
  xMultiComponentFactory = xContext.getServiceManager();

  Object oDesktop = null;
  try {
   oDesktop = xMultiComponentFactory.createInstanceWithContext(
     "com.sun.star.frame.Desktop", xContext);
  } catch (Exception e) {
   e.printStackTrace();
  }

  XComponentLoader xCLoader = (XComponentLoader) UnoRuntime
    .queryInterface(XComponentLoader.class, oDesktop);

  XComponent document = null;
  try {
   document = xCLoader.loadComponentFromURL(
     "private:factory/swriter", "_blank", 0, new PropertyValue[0]);
  } catch (IOException e) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  }
  
  XTextDocument aTextDocument = (XTextDocument) UnoRuntime
    .queryInterface(com.sun.star.text.XTextDocument.class, document);
  XText xText = aTextDocument.getText();
  xText.insertString(xText.getEnd(), "Hello OpenOffice3 UNO Java World!",
    false);
 }
}


Finally there is result