Example: Fields in a Template

From Apache OpenOffice Wiki
Jump to: navigation, search

All following code samples are contained in TextDocuments.java. This file is located in the Samples folder that comes with the resources for the developer's manual.

The examples use the environment from chapter First Steps, for instance, connecting using the getRemoteServiceManager() method.

We want to use a template file containing text fields and bookmarks and insert text into the fields and at the cursor position. The suitable template file TextTemplateWithUserFields.odt lies in the Samples folder, as well. Edit the path to this file below before running the sample.

The first step is to load the file as a template, so that Apache OpenOffice creates a new, untitled document. As in the chapter First Steps, we have to connect, get the Desktop object, query its XComponentLoader interface and call loadComponentFromUrl(). This time we tell Apache OpenOffice how it should load the file. The key for loading parameters is the sequence of PropertyValue structs passed to loadComponentFromUrl(). The appropriate PropertyValue name is AsTemplate and we have to set AsTemplate to true.

  /** Load a document as template */
  protected XComponent newDocComponentFromTemplate(String loadUrl) throws java.lang.Exception {
      // get the remote service manager
      mxRemoteServiceManager = this.getRemoteServiceManager(unoUrl);
      // retrieve the Desktop object, we need its XComponentLoader
      Object desktop = mxRemoteServiceManager.createInstanceWithContext(
          "com.sun.star.frame.Desktop", mxRemoteContext);
      XComponentLoader xComponentLoader = (XComponentLoader)UnoRuntime.queryInterface(
          XComponentLoader.class, desktop);
      // define load properties according to com.sun.star.document.MediaDescriptor
      // the boolean property AsTemplate tells the office to create a new document
      // from the given file
      PropertyValue[] loadProps = new PropertyValue[1];
      loadProps[0] = new PropertyValue();
      loadProps[0].Name = "AsTemplate";
      loadProps[0].Value = new Boolean(true); 
      // load
      return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0, loadProps); 

Now that we are able to load a text document as a template, we will open an existing template file that contains five text fields and a bookmark. We want to demonstrate how to insert text at predefined positions in a document.

Text fields and bookmarks are supplied by the appropriate XTextFieldsSupplier and XBookmarksSupplier interfaces. Their fully qualified names are com.sun.star.text.XTextFieldsSupplier and com.sun.star.text.XBookmarksSupplier.

The XTextFieldsSupplier provides collections of text fields in our text. We use document variable fields for our purpose, which are com.sun.star.text.textfield.User services. All User fields have a field master that holds the actual content of the variable. Therefore, the TextFields collection, as well as the FieldMasters are required for our example. We get the field masters for the five fields by name and set their Content property. Finally, we refresh the text fields so that they reflect the changes made to the field masters.

The XBookmarksSupplier returns all bookmarks in our document. The collection of bookmarks is a com.sun.star.container.XNameAccess, so that the bookmarks are retrieved by name. Every object in a text supports the interface XTextContent that has a method getAnchor(). The anchor is the text range an object takes up, so getAnchor() retrieves is a XTextRange. From the chapter First Steps, a com.sun.star.text.XTextRange allows setting the string of a text range. Our bookmark is a text content and therefore must support XTextContent. Inserting text at a bookmark position is straightforward: get the anchor of the bookmark and set its string.

  /** Sample for use of templates
      This sample uses the file TextTemplateWithUserFields.odt from the Samples folder.
      The file contains a number of User text fields (Variables - User) and a bookmark
      which we use to fill in various values
  protected void templateExample() throws java.lang.Exception {
      // create a small hashtable that simulates a rowset with columns
      Hashtable recipient = new Hashtable();
      recipient.put("Company", "Manatee Books");
      recipient.put("Contact", "Rod Martin");
      recipient.put("ZIP", "34567");
      recipient.put("City", "Fort Lauderdale");
      recipient.put("State", "Florida");
      // load template with User fields and bookmark
      XComponent xTemplateComponent = newDocComponentFromTemplate(
      // get XTextFieldsSupplier and XBookmarksSupplier interfaces from document component
      XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier)UnoRuntime.queryInterface(
          XTextFieldsSupplier.class, xTemplateComponent);
      XBookmarksSupplier xBookmarksSupplier = (XBookmarksSupplier)UnoRuntime.queryInterface(
          XBookmarksSupplier.class, xTemplateComponent);
      // access the TextFields and the TextFieldMasters collections
      XNameAccess xNamedFieldMasters = xTextFieldsSupplier.getTextFieldMasters();
      XEnumerationAccess xEnumeratedFields = xTextFieldsSupplier.getTextFields();
      // iterate over hashtable and insert values into field masters
      java.util.Enumeration keys = recipient.keys();
      while (keys.hasMoreElements()) {
          // get column name
          String key = (String)keys.nextElement();
          // access corresponding field master
          Object fieldMaster = xNamedFieldMasters.getByName(
              "com.sun.star.text.fieldmaster.User." + key);
          // query the XPropertySet interface, we need to set the Content property
          XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(
              XPropertySet.class, fieldMaster);
          // insert the column value into field master
          xPropertySet.setPropertyValue("Content", recipient.get(key));
      // afterwards we must refresh the textfields collection
      XRefreshable xRefreshable = (XRefreshable)UnoRuntime.queryInterface(
          XRefreshable.class, xEnumeratedFields);
      // accessing the Bookmarks collection of the document
      XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks();
      // find the bookmark named "Subscription"
      Object bookmark = xNamedBookmarks.getByName("Subscription");
      // we need its XTextRange which is available from getAnchor(), 
      // so query for XTextContent
      XTextContent xBookmarkContent = (XTextContent)UnoRuntime.queryInterface(
          XTextContent.class, bookmark);
      // get the anchor of the bookmark (its XTextRange)
      XTextRange xBookmarkRange = xBookmarkContent.getAnchor();
      // set string at the bookmark position
      xBookmarkRange.setString("subscription for the Manatee Journal");
Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages