Extracción de metadatos MS Office <--> Alfresco

cancel
Showing results for 
Search instead for 
Did you mean: 
kylian
Member II

Extracción de metadatos MS Office <--> Alfresco

Buenos días,

Tengo un par de dudas referentes a la extracción de metadatos con Alfresco.

Necesito exportar los datos introducidos en un wizard a una plantilla de documento Word. Los datos a exportar los gestiono como properties del propio wizard

Así por ejemplo si tengo generado un wizard de nombre "MyWizard" necesitaría exportar la información que almaceno en "nombreRepresentante"

<managed-bean>
      <managed-bean-name>MyWizard</managed-bean-name>
                 …
                 <managed-property>
         <property-name>nombreRepresentante</property-name>
         <value></value>
            </managed-property>
        …
        </managed-bean>

   <h:inputText id="nombreRepresentante"
value="#{WizardManager.bean.nombreRepresentante}" />

Y que partiendo de un documento Word ya predefinido, pueda insertar ese valor dinámico en el documento Word (¿asociar esa property a un field de Word?)

Estoy mirando la forma de poder hacerlo pero estoy algo perdido de momento.

¿Alguien podría orientarme un poco acerca de los pasos necesarios, la viabilidad de lo que propongo o en su defecto algún documento o post de referencia que me pueda ayudar?

Por otra parte…, ¿El paso inverso podría realizarse?, es decir, partiendo de un doc ya relleno, importar campos concretos del mismo (por ejemplo, el mismo "nombreRepresentante" que antes comentaba) asociándolos al wizard realizado en Alfresco?

Gracias por anticipado.
6 Replies
venzia
Senior Member

Re: Extracción de metadatos MS Office <--> Alfresco

Si entrar en detalles de desarrollo te comento :
Y que partiendo de un documento Word ya predefinido, pueda insertar ese valor dinámico en el documento Word (¿asociar esa property a un field de Word?)
Este planteamiento de mapeo de property a field de word es válido.

¿Alguien podría orientarme un poco acerca de los pasos necesarios, la viabilidad de lo que propongo o en su defecto algún documento o post de referencia que me pueda ayudar?
Creo que lo que necesitas es lo siguiente :
1-Recoger los valores de las propiedades en el paso 1 del wizard (esto creo que ya lo tienes).
¿2?-Seleccionar la plantilla word en la que incluiremos estos valores (esto se puede evitar si la tienes en un path específico de alfresco).
3-Buscar "marcadores" o en su defecto "campos" cuyo nombre coincida con el de la propiedad e incluir el valor en el mismo. Para realizar este proceso supongo tendras que tirar del api de openoffice que trae alfresco (el mismo que utiliza para la transformacion de formatos de documento por ejemplo). Tendrás que documentarte algo en este aspecto, pero seguro que obtienes funciones o metodos que te permiten trabajar con este tipo de elementos ("bookmarks", "fields", etc..).
Por otra parte…, ¿El paso inverso podría realizarse?, es decir, partiendo de un doc ya relleno, importar campos concretos del mismo (por ejemplo, el mismo "nombreRepresentante" que antes comentaba) asociándolos al wizard realizado en Alfresco?
1-Seleccionar el fichero.
2-Buscar todos sus "marcadores" o "campos" comprobando si existe en el wizard algun property con el mismo nombre para incluir el valor encontrado en el marcador.
De cualquier forma, este caso inverso lo veo, a priori, algo mas complejo.

Espero haber aportado algo de luz :wink: .
Saludos,
kylian
Member II

Re: Extracción de metadatos MS Office <--> Alfresco

Muchas gracias por la respuesta, exactamente, mediante la API de OpenOffice y haciendo uso de bookmarks he sido capaz de realizar lo que indicaba en la pregunta inicial (tanto la exportación como la importación).

Un saludo
venzia
Senior Member

Re: Extracción de metadatos MS Office <--> Alfresco

Me alegro que al final haya salido  :wink:.
P.D.: y seria un buen aporte para la comunidad conocer los detalles de la implementación que has llevado a cabo Smiley Tongue  (aunque esto ya es cosa tuya Smiley Surprisedops: )
Saludos!
kylian
Member II

Re: Extracción de metadatos MS Office <--> Alfresco

Sin problema, en cuanto tenga un ratillo pondré alguna referencia web que me ha sido útil, y partes de mi código con los pasos básicos que he seguido  :wink:
venzia
Senior Member

Re: Extracción de metadatos MS Office <--> Alfresco

Por que no puedo darte un punto q si nooo! .. jeje  :mrgreen:
Esperamos ansiosos ese aporte.
Saludos!,
kylian
Member II

Re: Extracción de metadatos MS Office <--> Alfresco

El ejemplo realiza la exportación e importación de un documento que tuviese un unico campo, para el resto habría que extrapolar esta solución

Bean en el que defino el wizard con sus propiedades:

<managed-bean>
      <managed-bean-name>MRPABean</managed-bean-name>
      <managed-bean-class>com.xxx.alfresco.mrpa.MRPABean</managed-bean-class>
      <managed-bean-scope>session</managed-bean-scope>
      <!–  DATOS  DEL TITULAR –>
      <managed-property>
         <property-name>titularigMRPA</property-name>
         <value></value>
      </managed-property>
          </managed-bean>


public class MRPABean {
        …
   public String getTitularigMRPA() {
      return titularigMRPA;
   }
          public void setTitularigMRPA(String titularigMRPA) {
      this.titularigMRPA = titularigMRPA;
   }

En la jsp de vista

   <h:inputText id="titularigMRPA" value="#{MRPABean.titularigMRPA}"
      maxlength="1024" size="35" />
         …
   <h:commandButton id="generatedocMRPA-button" styleClass="wizardButton"
      value="Generar documentos" immediate="false"
      action="#{MRPABean.exportData}" />
         <h:commandButton id="importdoc-buttonMRPA" styleClass="wizardButton"
      value="Importar documento" immediate="false"
      action="#{MRPABean.importData}"
        

Exportación ("bean" es el MRPABean antes comentado)

WriterHelperMRPA.createDoc("MRPA",
               "C:\\Alfresco\\plantillas\\PlantillaMRPA.doc", bean, true);

Importación


WriterHelperMRPA.importacion("MRPA",
                  "C:\\Alfresco\\plantillas\\MRPA.doc",
                  wizard, true);

Clase WriterHelper donde se implementa toda la lógica que permite la exportación e importación de bookmarks


package com.XXX.alfresco.mrpa;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import src.ooo.connector.BootstrapSocketConnector;

import com.sun.star.awt.XWindow;
import com.sun.star.beans.Property;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XPropertySetInfo;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XNameAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XController;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XEventListener;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.style.XStyleFamiliesSupplier;
import com.sun.star.text.XBookmarksSupplier;
import com.sun.star.text.XText;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextFieldsSupplier;
import com.sun.star.text.XTextRange;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

/**
* Creates and OpenOffice Writer document.
* <p>
*
* @author XXX
*/
public class WriterHelperMRPA {

   private static XComponentContext context;

   private static final int REPLACE_ALL = 0;
   private static final int ADD_SENTENCE = 1;
   private static final int ADD_PARAGRAPH = 2;

   private static final String MS_WORD_SAVE_FORMAT = "MS Word 97";
   private static final String PDF_SAVE_FORMAT = "writer_pdf_Export";
   private static final String OPEN_OFFICE_SAVE_FORMAT = "Writer8";

   /** Constructor. */
   public WriterHelperMRPA() {
   }

   /**
    * Create an OpenOffice Writer document and make it visible on the screen.
    * Call the saveDoc method to save the document to a file.
    * <p>
    *
    * @return The 'handle' to the document.
    * @param docTitle
    *            The title of the document. This will show up in the title bar
    *            of the document window.
    * @param templateFile
    *            The absolute path of a template file. If not null, the newly
    *            created file will initially be an exact duplicate of this
    *            file. Typically, the template file contains bookmarks where
    *            this application can insert text, images, charts, etc. (The
    *            template can be created using OpenOffice Writer). If this
    *            parameter is null, the new document will be blank.
    * @param isUserEditable
    *            True = allow user to manipulate/edit the Writer document
    *            window. False = make the Writer document window uneditable.
    */
   public static XComponent createDoc(String docTitle, String templateFile,
         MRPABean wizard, boolean isUserEditable) throws java.lang.Exception {

      XComponent document = null;

      try {
         // Get remote service manager. We only need one instance regardless
         // of the number of documents we create.
         if (context == null) {
            try {
               String oooExeFolder = "C:/Alfresco/OpenOffice/OpenOffice.org 3/program";
               context = BootstrapSocketConnector.bootstrap(oooExeFolder);
            } catch (BootstrapException e) {
               throw new java.lang.Exception(e);
            }
         }
         XMultiComponentFactory serviceManager = context.getServiceManager();

         // Retrieve the Desktop object and get its XComponentLoader.
         Object desktop = serviceManager.createInstanceWithContext(
               "com.sun.star.frame.Desktop", context);
         XComponentLoader loader = (XComponentLoader) UnoRuntime
               .queryInterface(XComponentLoader.class, desktop);

         // Define general document properties (see
         // com.sun.star.document.MediaDescriptor for the possibilities).
         ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
         PropertyValue p = null;
         if (templateFile != null) {
            p = new PropertyValue();
            p.Name = "AsTemplate";
            p.Value = new Boolean(true);
            props.add(p);
         }
         if ((docTitle != null) && (docTitle.length() > 0)) {
            p = new PropertyValue();
            p.Name = "DocumentTitle";
            p.Value = docTitle;
            props.add(p);
         }
         // The following code will make the document initially invisible.
         // Do this if you will be placing lots of data into it, so the
         // user doesn't have to watch it being constructed. You can bring
         // it into view later.
         /*
          * p = new PropertyValue(); p.Name = "Hidden"; p.Value = new
          * Boolean(true); props.add(p);
          */

         PropertyValue[] properties = new PropertyValue[props.size()];
         props.toArray(properties);

         // Create the document
         // (see com.sun.star.frame.XComponentLoader for argument details).

         document = null;

         if (templateFile != null) {
            // Create a new document that is a duplicate of the template.
            String templateFileURL = filePathToURL(templateFile);
            document = loader.loadComponentFromURL(templateFileURL, // URL
                  // of
                  // templateFile.
                  "_blank", // Target frame name (_blank creates new
                  // frame).
                  0, // Search flags.
                  properties); // Document attributes.
         } else {
            // Create a new document.
            String docType = "swriter";
            String newDocURL = "private:factory/" + docType;
            document = loader.loadComponentFromURL(newDocURL, // URL for
                  // creating
                  // a new
                  // document.
                  "_blank", // Target frame name (_blank creates a new
                  // frame).
                  0, // Search flags.
                  properties); // Document properties.
         }

         // Fetch field and style information.
         // NOTE: I have not found a use for these yet.

         XTextFieldsSupplier fieldSupplier = (XTextFieldsSupplier) UnoRuntime
               .queryInterface(XTextFieldsSupplier.class, document);
         XStyleFamiliesSupplier styleFamiliesSupplier = (XStyleFamiliesSupplier) UnoRuntime
               .queryInterface(XStyleFamiliesSupplier.class, document);

         // Get the document's bookmark name supplier.

         XBookmarksSupplier bookmarksSupplier = (XBookmarksSupplier) UnoRuntime
               .queryInterface(XBookmarksSupplier.class, document);

         // Add a document displose listener so we can know if the user
         // manually exits the Writer window.

         document.addEventListener(new XEventListener() {
            public void disposing(EventObject e) {
               // TBD
            }
         });

         // Control whether the user can edit the displayed document.
         if (!isUserEditable) {
            XModel model = (XModel) UnoRuntime.queryInterface(XModel.class,
                  document);
            XController c = model.getCurrentController();
            XFrame frame = c.getFrame();
            XWindow window = frame.getContainerWindow();
            window.setEnable(isUserEditable);
         }

         // /////////////////////////////////////////////////////
         // Example of inserting text into a bookmarked field
         // /////////////////////////////////////////////////////

         bookmarksMRPA(bookmarksSupplier, wizard);

         saveDOC(document, "C:\\Alfresco\\plantillas\\MRPA.doc", true);

         saveODT(document, "C:\\Alfresco\\plantillas\\MRPA.odt", true);

         savePDF(document, "C:\\Alfresco\\plantillas\\MRPA.pdf", true);

         // NOTE: if the inserted text needs to have a particular font
         // and/or color, then do the following in the above code:
         //
         // 1. Before calling setString, save the XTextCursor's property set.
         // 2. Modify the XTextCursor's property set as desired. Following
         // are the names of properties typically modified for color and
         // font: CharColor, CharFontName, CharFontFamily, CharFontPitch,
         // CharFontPosture, CharFontWeight, CharHeight. (Call the
         // showProperties method on the XTextCursor's property set to
         // see the required data types).
         // 3. After calling setString, restore the XTextCursor's original
         // properties.

      } catch (com.sun.star.uno.Exception e) {
         throw new java.lang.Exception(e);
      }

      return document;
   }

   /**
    * Se sustituyen los valores de los Bookmarks (marcadores en la plantilla
    * del documento MRPA) de acuerdo a los valores que hemos obtenido en la
    * capa de vista para la página del wizard adecuada
    *
    * @param bookmarksSupplier
    * @param wizard
    * @throws Exception
    */
   public static void bookmarksMRPA(XBookmarksSupplier bookmarksSupplier,
         MRPABean wizard) throws Exception {

      // Datos generales y del titular

      changeBookmarksValues(bookmarksSupplier, "titularigMRPA", wizard
            .getTitularigMRPA());

   }

   /**
    * Se sustituyen los valores de los Bookmarks (marcadores en la plantilla
    * del documento MRPA) de acuerdo a los valores que hemos obtenido en la
    * capa de vista para la página del wizard adecuada
    *
    * @param bookmarksSupplier
    * @param wizard
    * @throws Exception
    */
   public static void bookmarksImportMRPA(
         XBookmarksSupplier bookmarksSupplier, MRPABean wizard)
         throws Exception {

      // Datos generales y del titular

      wizard.setTitularigMRPA(changeBookmarksValuesImport(bookmarksSupplier,
            "titularigMRPA"));
      

   }

   /**
    * Sustituimos los valores de los BOOKMARKS
    *
    * @param bookmarksSupplier
    * @param bookmarkName
    * @param textToInsert
    * @throws Exception
    */
   public static String changeBookmarksValuesImport(
         XBookmarksSupplier bookmarksSupplier, String bookmarkName)
         throws Exception

   {
      // Get the XTextRange associated with the specified bookmark.
      XTextRange overallTextRange = getBookmarkTextRange(bookmarksSupplier,
            bookmarkName);

      // XText is the main interface to a distinct text unit, for
      // example, the main text of a document, the text for headers
      // and footers, or a single cell of a table. It's
      // insertTextContent method allows insertion of a text table,
      // text frame, or text field.

      // Extraemos el texto
      XText textContent = overallTextRange != null ? overallTextRange
            .getText() : null;

      String text = textContent != null ? textContent.getString() : "";

      return text;
   }

   /**
    * Sustituimos los valrores de los BOOKMARKS
    *
    * @param bookmarksSupplier
    * @param bookmarkName
    * @param textToInsert
    * @throws Exception
    */
   public static void changeBookmarksValues(
         XBookmarksSupplier bookmarksSupplier, String bookmarkName,
         String textToInsert) throws Exception

   {
      // Get the XTextRange associated with the specified bookmark.
      XTextRange overallTextRange = getBookmarkTextRange(bookmarksSupplier,
            bookmarkName);
      XTextRange textRange = null;

      // XText is the main interface to a distinct text unit, for
      // example, the main text of a document, the text for headers
      // and footers, or a single cell of a table. It's
      // insertTextContent method allows insertion of a text table,
      // text frame, or text field.
      XText textContent = overallTextRange.getText();

      // XTextCursor provides methods to move the insertion/extraction
      // cursor within an XText text unit. In this case, we're
      // defaulting the cursor to the beginning of the text unit.
      XTextCursor textCursor = textContent.createTextCursor();

      // Insert the given text at the bookmark position according to
      // the desired insertion mode.
      int insertMode = REPLACE_ALL;

      if (insertMode == REPLACE_ALL) {
         overallTextRange.setString(textToInsert);
         textCursor.gotoEnd(true);
      } else if (insertMode == ADD_SENTENCE) {
         textCursor.gotoEnd(false);
         textCursor.setString(textToInsert);
         textCursor.gotoEnd(true);
      } else if (insertMode == ADD_PARAGRAPH) {
         textCursor.gotoEnd(false);
         textCursor.setString("\n" + textToInsert);
         textCursor.gotoEnd(true);
      }
   }

   /**
    * Save a given document to a specified file.
    * <p>
    *
    * @param document
    *            The 'handle' to the document.
    * @param saveFile
    *            The full path of the file in which to save the document. If
    *            null, this method will do nothing.
    * @param overwrite
    *            If true, and the file already exists, it will be overwritten.
    *            Otherwise an exception will be thrown.
    */
   public static void savePDF(XComponent document, String saveFile,
         boolean overwrite) throws java.lang.Exception,
         MalformedURLException {

      try {
         if ((saveFile == null) || (saveFile.trim().length() == 0)) {
            return;
         }
         if (!overwrite) {
            File f = new File(saveFile);
            if (f.exists()) {
               throw new java.lang.Exception("File " + saveFile
                     + " already exists; overwriting disabled.");
            }
         }

         String saveFileURL = filePathToURL(saveFile);
         XStorable storable = (XStorable) UnoRuntime.queryInterface(
               XStorable.class, document);

         PropertyValue[] properties = new PropertyValue[1];
         PropertyValue p = new PropertyValue();
         p.Name = "FilterName";
         p.Value = PDF_SAVE_FORMAT;
         properties[0] = p;

         storable.storeToURL(saveFileURL, properties);

      } catch (com.sun.star.uno.Exception e) {
         throw new java.lang.Exception(e);
      }
   }

   /**
    * Save a given document to a specified .DOC file.
    * <p>
    *
    * @param document
    *            The 'handle' to the document.
    * @param saveFile
    *            The full path of the file in which to save the document. If
    *            null, this method will do nothing.
    * @param overwrite
    *            If true, and the file already exists, it will be overwritten.
    *            Otherwise an exception will be thrown.
    */
   public static void saveDOC(XComponent document, String saveFile,
         boolean overwrite) throws java.lang.Exception,
         MalformedURLException {

      try {
         if ((saveFile == null) || (saveFile.trim().length() == 0)) {
            return;
         }
         if (!overwrite) {
            File f = new File(saveFile);
            if (f.exists()) {
               throw new java.lang.Exception("File " + saveFile
                     + " already exists; overwriting disabled.");
            }
         }

         String saveFileURL = filePathToURL(saveFile);
         XStorable storable = (XStorable) UnoRuntime.queryInterface(
               XStorable.class, document);

         PropertyValue[] properties = new PropertyValue[1];
         PropertyValue p = new PropertyValue();
         p.Name = "FilterName";
         p.Value = MS_WORD_SAVE_FORMAT;
         properties[0] = p;

         storable.storeAsURL(saveFileURL, properties);

      } catch (com.sun.star.uno.Exception e) {
         throw new java.lang.Exception(e);
      }
   }

   /**
    * Save a given document to a specified .ODT file.
    * <p>
    *
    * @param document
    *            The 'handle' to the document.
    * @param saveFile
    *            The full path of the file in which to save the document. If
    *            null, this method will do nothing.
    * @param overwrite
    *            If true, and the file already exists, it will be overwritten.
    *            Otherwise an exception will be thrown.
    */
   public static void saveODT(XComponent document, String saveFile,
         boolean overwrite) throws java.lang.Exception,
         MalformedURLException {

      try {
         if ((saveFile == null) || (saveFile.trim().length() == 0)) {
            return;
         }
         if (!overwrite) {
            File f = new File(saveFile);
            if (f.exists()) {
               throw new java.lang.Exception("File " + saveFile
                     + " already exists; overwriting disabled.");
            }
         }

         String saveFileURL = filePathToURL(saveFile);
         XStorable storable = (XStorable) UnoRuntime.queryInterface(
               XStorable.class, document);

         PropertyValue[] properties = new PropertyValue[1];
         PropertyValue p = new PropertyValue();
         p.Name = "FilterName";
         p.Value = OPEN_OFFICE_SAVE_FORMAT;
         properties[0] = p;

         storable.storeAsURL(saveFileURL, properties);

      } catch (com.sun.star.uno.Exception e) {
         throw new java.lang.Exception(e);
      }
   }

   /** Get a bookmarked field's TextRange. */
   private static XTextRange getBookmarkTextRange(
         XBookmarksSupplier bookmarksSupplier, String bookmarkName)
         throws java.lang.Exception {

      XTextRange textRange = null;
      try {
         // Get the collection of bookmarks in the document.
         XNameAccess bookmarkNames = bookmarksSupplier.getBookmarks();

         // Find the bookmark having the given name.
         Object bmk = null;
         try {
            bmk = bookmarkNames.getByName(bookmarkName);
         } catch (NoSuchElementException e) {
            System.out.println( bmk);
         }
         if (bmk == null) {

            throw new java.lang.Exception("Cannot find bookmark '"
                  + bookmarkName + "'");
         }

         // Get the bookmark's XTextContent. It allows objects to be
         // inserted into a text and provides their location within a
         // text after insertion.

         XTextContent bookmarkContent = (XTextContent) UnoRuntime
               .queryInterface(XTextContent.class, bmk);

         // Get the bookmark's XTextRange. It describes the object's
         // position within the text and provides access to the text.

         textRange = bookmarkContent.getAnchor();

      } catch (com.sun.star.uno.Exception e) {
         throw new java.lang.Exception(e);
      }

      return textRange;
   }

   /** Convert a file path to URL format. */
   private static String filePathToURL(String file) {
      File f = new File(file);
      StringBuffer sb = new StringBuffer("file:///");
      try {
         sb.append(f.getCanonicalPath().replace('\\', '/'));
      } catch (IOException e) {
      }
      return sb.toString();
   }

   /**
    * Dump a given XPropertySet. This comes in handy because it's
    * otherwise hard to know all the properties available within a given UNO
    * component's property set. You can use UnoRuntime.queryInterface to fetch
    * the component's property set, then call this method to dump it.
    */
   private void showProperties(String title, XPropertySet pSet) {
      System.out.println("\n" + title + "\n");
      XPropertySetInfo info = pSet.getPropertySetInfo();
      Property[] props = info.getProperties();
      if (props != null) {
         try {
            for (int i = 0; i < props.length; i++) {
               Property p = props[i];
               String value = "<null>";
               try {
                  Object o = (Object) pSet.getPropertyValue(p.Name);
                  if (o != null) {
                     value = o.toString();
                  }
               } catch (java.lang.Exception e) {
                  value = "<null>";
               }
               System.out.println(" Name = " + p.Name + ", Type = "
                     + p.Type + ", Value = " + value);
            }
         } catch (java.lang.Exception e) {
            e.printStackTrace();
         }
      }
   }

   /**
    * Create an OpenOffice Writer document and make it visible on the screen.
    * Call the saveDoc method to save the document to a file.
    * <p>
    *
    * @return The 'handle' to the document.
    * @param docTitle
    *            The title of the document. This will show up in the title bar
    *            of the document window.
    * @param templateFile
    *            The absolute path of a template file. If not null, the newly
    *            created file will initially be an exact duplicate of this
    *            file. Typically, the template file contains bookmarks where
    *            this application can insert text, images, charts, etc. (The
    *            template can be created using OpenOffice Writer). If this
    *            parameter is null, the new document will be blank.
    * @param isUserEditable
    *            True = allow user to manipulate/edit the Writer document
    *            window. False = make the Writer document window uneditable.
    */
   public static XComponent importDoc(String docTitle, String templateFile,
         MRPABean wizard, boolean isUserEditable) throws java.lang.Exception {

      XComponent document = null;

      try {
         // Get remote service manager. We only need one instance regardless
         // of the number of documents we create.

         System.out.println(context);
         try {
            String oooExeFolder = "C:/Alfresco/OpenOffice/OpenOffice.org 3/program";
            context = BootstrapSocketConnector.bootstrap(oooExeFolder);
         } catch (BootstrapException e) {
            throw new java.lang.Exception(e);
         }

         XMultiComponentFactory serviceManager = null;
         try {
            serviceManager = context.getServiceManager();
         } catch (com.sun.star.lang.DisposedException e) {
         }

         // Retrieve the Desktop object and get its XComponentLoader.
         Object desktop = serviceManager.createInstanceWithContext(
               "com.sun.star.frame.Desktop", context);
         XComponentLoader loader = (XComponentLoader) UnoRuntime
               .queryInterface(XComponentLoader.class, desktop);

         // Define general document properties (see
         // com.sun.star.document.MediaDescriptor for the possibilities).
         ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
         PropertyValue p = null;
         if (templateFile != null) {
            p = new PropertyValue();
            p.Name = "Hidden";
            p.Value = new Boolean(true);
            props.add(p);
         }
         if ((docTitle != null) && (docTitle.length() > 0)) {
            p = new PropertyValue();
            p.Name = "DocumentTitle";
            p.Value = docTitle;
            props.add(p);
         }
         // The following code will make the document initially invisible.
         // Do this if you will be placing lots of data into it, so the
         // user doesn't have to watch it being constructed. You can bring
         // it into view later.
         /*
          * p = new PropertyValue(); p.Name = "Hidden"; p.Value = new
          * Boolean(true); props.add(p);
          */

         PropertyValue[] properties = new PropertyValue[props.size()];
         props.toArray(properties);

         // Create the document
         // (see com.sun.star.frame.XComponentLoader for argument details).

         document = null;

         if (templateFile != null) {
            // Create a new document that is a duplicate of the template.
            String templateFileURL = filePathToURL(templateFile);
            document = loader.loadComponentFromURL(templateFileURL, // URL
                  // of
                  // templateFile.
                  "_blank", // Target frame name (_blank creates new
                  // frame).
                  0, // Search flags.
                  properties); // Document attributes.
         } else {
            // Create a new document.
            String docType = "swriter";
            String newDocURL = "private:factory/" + docType;
            document = loader.loadComponentFromURL(newDocURL, // URL for
                  // creating
                  // a new
                  // document.
                  "_blank", // Target frame name (_blank creates a new
                  // frame).
                  0, // Search flags.
                  properties); // Document properties.
         }

         importacion(docTitle, "C:\\Alfresco\\plantillas\\MRPA.doc", wizard,
               true);

      } catch (com.sun.star.uno.Exception e) {
         throw new java.lang.Exception(e);
      }

      return document;
   }

   /**
    * Create an OpenOffice Writer document and make it visible on the screen.
    * Call the saveDoc method to save the document to a file.
    * <p>
    *
    * @return The 'handle' to the document.
    * @param docTitle
    *            The title of the document. This will show up in the title bar
    *            of the document window.
    * @param templateFile
    *            The absolute path of a template file. If not null, the newly
    *            created file will initially be an exact duplicate of this
    *            file. Typically, the template file contains bookmarks where
    *            this application can insert text, images, charts, etc. (The
    *            template can be created using OpenOffice Writer). If this
    *            parameter is null, the new document will be blank.
    * @param isUserEditable
    *            True = allow user to manipulate/edit the Writer document
    *            window. False = make the Writer document window uneditable.
    */
   public static XComponent importacion(String docTitle, String templateFile,
         MRPABean wizard, boolean isUserEditable) throws java.lang.Exception {

      XComponent document = null;

      try {
         // Get remote service manager. We only need one instance regardless
         // of the number of documents we create.
         if (context == null) {
            try {
               String oooExeFolder = "C:/Alfresco/OpenOffice/OpenOffice.org 3/program";
               context = BootstrapSocketConnector.bootstrap(oooExeFolder);
            } catch (BootstrapException e) {
               throw new java.lang.Exception(e);
            }
         }
         XMultiComponentFactory serviceManager = context.getServiceManager();

         System.out.println("-1");

         // Retrieve the Desktop object and get its XComponentLoader.
         Object desktop = serviceManager.createInstanceWithContext(
               "com.sun.star.frame.Desktop", context);
         XComponentLoader loader = (XComponentLoader) UnoRuntime
               .queryInterface(XComponentLoader.class, desktop);

         // Define general document properties (see
         // com.sun.star.document.MediaDescriptor for the possibilities).
         ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
         PropertyValue p = null;
         if (templateFile != null) {
            p = new PropertyValue();
            p.Name = "Hidden";
            p.Value = new Boolean(true);
            props.add(p);
         }
         if ((docTitle != null) && (docTitle.length() > 0)) {
            p = new PropertyValue();
            p.Name = "DocumentTitle";
            p.Value = docTitle;
            props.add(p);
         }
         // The following code will make the document initially invisible.
         // Do this if you will be placing lots of data into it, so the
         // user doesn't have to watch it being constructed. You can bring
         // it into view later.
         /*
          * p = new PropertyValue(); p.Name = "Hidden"; p.Value = new
          * Boolean(true); props.add(p);
          */

         PropertyValue[] properties = new PropertyValue[props.size()];
         props.toArray(properties);

         // Create the document
         // (see com.sun.star.frame.XComponentLoader for argument details).

         document = null;

         if (templateFile != null) {
            // Create a new document that is a duplicate of the template.
            String templateFileURL = filePathToURL(templateFile);
            document = loader.loadComponentFromURL(templateFileURL, // URL
                  // of
                  // templateFile.
                  "_blank", // Target frame name (_blank creates new
                  // frame).
                  0, // Search flags.
                  properties); // Document attributes.
         } else {
            // Create a new document.
            String docType = "swriter";
            String newDocURL = "private:factory/" + docType;
            document = loader.loadComponentFromURL(newDocURL, // URL for
                  // creating
                  // a new
                  // document.
                  "_blank", // Target frame name (_blank creates a new
                  // frame).
                  0, // Search flags.
                  properties); // Document properties.
         }

         // Fetch field and style information.
         // NOTE: I have not found a use for these yet.

         XTextFieldsSupplier fieldSupplier = (XTextFieldsSupplier) UnoRuntime
               .queryInterface(XTextFieldsSupplier.class, document);
         XStyleFamiliesSupplier styleFamiliesSupplier = (XStyleFamiliesSupplier) UnoRuntime
               .queryInterface(XStyleFamiliesSupplier.class, document);

         // Get the document's bookmark name supplier.

         XBookmarksSupplier bookmarksSupplier = (XBookmarksSupplier) UnoRuntime
               .queryInterface(XBookmarksSupplier.class, document);

         // Add a document displose listener so we can know if the user
         // manually exits the Writer window.

         document.addEventListener(new XEventListener() {
            public void disposing(EventObject e) {
               // TBD
            }
         });

         // Control whether the user can edit the displayed document.
         if (!isUserEditable) {
            XModel model = (XModel) UnoRuntime.queryInterface(XModel.class,
                  document);
            XController c = model.getCurrentController();
            XFrame frame = c.getFrame();
            XWindow window = frame.getContainerWindow();
            window.setEnable(isUserEditable);
         }

         // /////////////////////////////////////////////////////
         // Example of inserting text into a bookmarked field
         // /////////////////////////////////////////////////////

         bookmarksImportMRPA(bookmarksSupplier, wizard);

         // NOTE: if the inserted text needs to have a particular font
         // and/or color, then do the following in the above code:
         //
         // 1. Before calling setString, save the XTextCursor's property set.
         // 2. Modify the XTextCursor's property set as desired. Following
         // are the names of properties typically modified for color and
         // font: CharColor, CharFontName, CharFontFamily, CharFontPitch,
         // CharFontPosture, CharFontWeight, CharHeight. (Call the
         // showProperties method on the XTextCursor's property set to
         // see the required data types).
         // 3. After calling setString, restore the XTextCursor's original
         // properties.

      } catch (com.sun.star.uno.Exception e) {
         throw new java.lang.Exception(e);
      }

      return document;
   }

}


Únicamente falta añadir los bookmarks en las plantillas Word que servirían de modelo para este proceso, la idea es añadir un marcador en la posición concreta del documento con un nombre exactamente igual al de la property.

Con "eso" es suficiente, jeje

En mi caso tuve algún problema con la conexión a OpenOffice, la solución fue hacer lo que se indica en este post del foro de OpenOffice http://user.services.openoffice.org/en/forum/viewtopic.php?f=44&t=2520

Un saludo

PD: Ver http://www.oooforum.org/forum/viewtopic.phtml?t=67936
http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Text/Bookmarks y para el manejo de checkboxes http://www.oooforum.org/forum/viewtopic.phtml?t=15253