martedì 23 novembre 2010

OpenOffice.org Annotations in java

I couldn't find a way to add Annotations (com.sun.star.text.textfield.Annotation) to OpenOffice (writer) documents through the UNO api in java: after some testing I figured it out how to do it, so I post here some code that you can find useful (hope). One important thing I was missing was how to create a MultiServiceFactory from a text document: this is explayned in the code below.
The only things you need to run this code are a valid XTextDocument and the XCursor indicating the place where you want the annotation to appear.


// get an XMultiServiceFactory from the XTextDocument
XText xText = xTextDocument.getText();
XMultiServiceFactory xMSF = (XMultiServiceFactory) UnoRuntime
      .queryInterface(XMultiServiceFactory.class, xTextDocument);
XTextField annotation = (XTextField) UnoRuntime.queryInterface(
      XTextField.class, xMSF.createInstance(
           "com.sun.star.text.textfield.Annotation"));
// set the annotation's property
XPropertySet xAnnotationProps = (XPropertySet) 
      UnoRuntime.queryInterface(XPropertySet.class, annotation);
xAnnotationProps.setPropertyValue("Author", author);
  xAnnotationProps.setPropertyValue("Content", text);
com.sun.star.util.Date date = new com.sun.star.util.Date();
date.Day = (short) day; date.Month = (short) month; date.Year = (short) year;
xAnnotationProps.setPropertyValue("Date", date);

// add the annotation at the XCursor position
xText.insertTextContent(xCursor, annotation, false);


Hope this helped

Nessun commento: