1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 import com.sun.star.awt.Point;
25 import com.sun.star.awt.Size;
26 import com.sun.star.awt.FontWeight;
27 
28 import com.sun.star.beans.PropertyState;
29 import com.sun.star.beans.PropertyValue;
30 import com.sun.star.beans.XPropertySet;
31 import com.sun.star.beans.XPropertyState;
32 
33 import com.sun.star.bridge.XUnoUrlResolver;
34 
35 import com.sun.star.comp.servicemanager.ServiceManager;
36 
37 import com.sun.star.connection.XConnector;
38 import com.sun.star.connection.XConnection;
39 
40 import com.sun.star.container.XNameAccess;
41 import com.sun.star.container.XNameContainer;
42 import com.sun.star.container.XNamed;
43 import com.sun.star.container.XIndexAccess;
44 import com.sun.star.container.XIndexReplace;
45 import com.sun.star.container.XEnumeration;
46 import com.sun.star.container.XEnumerationAccess;
47 
48 import com.sun.star.drawing.XShape;
49 import com.sun.star.drawing.XShapeGrouper;
50 import com.sun.star.drawing.XShapes;
51 import com.sun.star.drawing.XDrawPageSupplier;
52 
53 import com.sun.star.frame.XDesktop;
54 import com.sun.star.frame.XComponentLoader;
55 import com.sun.star.frame.XModel;
56 import com.sun.star.frame.XController;
57 
58 import com.sun.star.lang.XComponent;
59 import com.sun.star.lang.XMultiComponentFactory;
60 import com.sun.star.lang.XMultiServiceFactory;
61 import com.sun.star.lang.XServiceInfo;
62 
63 import com.sun.star.style.NumberingType;
64 import com.sun.star.style.XStyle;
65 import com.sun.star.style.XStyleFamiliesSupplier;
66 
67 import com.sun.star.table.XCell;
68 
69 import com.sun.star.text.ControlCharacter;
70 import com.sun.star.text.ReferenceFieldSource;
71 import com.sun.star.text.ReferenceFieldPart;
72 import com.sun.star.text.TextColumn;
73 import com.sun.star.text.TextContentAnchorType;
74 import com.sun.star.text.XAutoTextContainer;
75 import com.sun.star.text.XAutoTextGroup;
76 import com.sun.star.text.XAutoTextEntry;
77 import com.sun.star.text.XDependentTextField;
78 import com.sun.star.text.XDocumentIndex;
79 import com.sun.star.text.XFootnote;
80 import com.sun.star.text.XFootnotesSupplier;
81 import com.sun.star.text.XParagraphCursor;
82 import com.sun.star.text.XReferenceMarksSupplier;
83 import com.sun.star.text.XRelativeTextContentInsert;
84 import com.sun.star.text.XSentenceCursor;
85 import com.sun.star.text.XSimpleText;
86 import com.sun.star.text.XText;
87 import com.sun.star.text.XTextColumns;
88 import com.sun.star.text.XTextContent;
89 import com.sun.star.text.XTextCursor;
90 import com.sun.star.text.XTextDocument;
91 import com.sun.star.text.XTextField;
92 import com.sun.star.text.XTextFrame;
93 import com.sun.star.text.XTextRange;
94 import com.sun.star.text.XTextSection;
95 import com.sun.star.text.XTextTable;
96 import com.sun.star.text.XTextTableCursor;
97 import com.sun.star.text.XTextTablesSupplier;
98 import com.sun.star.text.XTextFieldsSupplier;
99 import com.sun.star.text.XBookmarksSupplier;
100 import com.sun.star.text.XTextViewCursorSupplier;
101 import com.sun.star.text.XTextViewCursor;
102 import com.sun.star.text.XPageCursor;
103 
104 import com.sun.star.text.XWordCursor;
105 
106 import com.sun.star.uno.AnyConverter;
107 import com.sun.star.uno.UnoRuntime;
108 import com.sun.star.uno.XComponentContext;
109 import com.sun.star.uno.XInterface;
110 import com.sun.star.uno.XNamingService;
111 
112 import com.sun.star.util.XRefreshable;
113 
114 import com.sun.star.frame.XStorable;
115 import com.sun.star.view.XPrintable;
116 
117 import java.lang.Math;
118 import java.util.Random;
119 import java.util.Hashtable;
120 
121 /*
122  * TextDocuments.java
123  *
124  * Created on 11. April 2002, 08:47
125  */
126 
127 /**
128  *
129  * @author Martin Gallwey, Dietrich Schulten
130  */
131 public class TextDocuments {
132     // adjust these constant to your local printer!
133     private static String sOutputDir;
134 
135     private String aPrinterName = "\\\\so-print\\xml3sof";
136 
137     private XComponentContext mxRemoteContext = null;
138     private XMultiComponentFactory mxRemoteServiceManager = null;
139     private XTextDocument mxDoc = null;
140     private XMultiServiceFactory mxDocFactory = null;
141     private XMultiServiceFactory mxFactory = null;
142     private XPropertySet mxDocProps = null;
143     private XText mxDocText = null;
144     private XTextCursor mxDocCursor = null;
145     private XTextContent mxFishSection = null;
146     private Random maRandom = null;
147 
148     /** Creates a new instance of TextDocuments */
TextDocuments()149     public TextDocuments() {
150     }
151 
152     /**
153      * @param args the command line arguments
154      */
main(String[] args)155     public static void main(String[] args) {
156     TextDocuments textDocuments1 = new TextDocuments();
157     try {
158             // output directory for store test;
159             sOutputDir = args[0];
160 
161             textDocuments1.runDemo();
162         }
163         catch (java.lang.Exception e){
164             System.out.println(e.getMessage());
165             e.printStackTrace();
166         }
167         finally {
168             System.exit(0);
169         }
170     }
171 
runDemo()172     protected void runDemo() throws java.lang.Exception {
173             storePrintExample(); // depends on printer name
174             templateExample();
175             viewCursorExample(); // makes changes to the current document,
176                                  // use with care
177             editingExample();
178     }
179 
180     /** Sample for use of templates
181      *  This sample uses the file TextTemplateWithUserFields.odt from the Samples
182      *  folder. The file contains a number of User text fields (Variables - User)
183      *  and a bookmark which we use to fill in various values
184      */
templateExample()185     protected void templateExample() throws java.lang.Exception {
186         // create a small hashtable that simulates a rowset
187         Hashtable recipient = new Hashtable();
188         recipient.put("Company", "Manatee Books");
189         recipient.put("Contact", "Rod Martin");
190         recipient.put("ZIP", "34567");
191         recipient.put("City", "Fort Lauderdale");
192         recipient.put("State", "Florida");
193 
194         // load template with User fields and bookmark
195         java.io.File sourceFile = new java.io.File("TextTemplateWithUserFields.odt");
196         StringBuffer sTemplateFileUrl = new StringBuffer("file:///");
197         sTemplateFileUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
198 
199         XComponent xTemplateComponent =
200             newDocComponentFromTemplate( sTemplateFileUrl.toString() );
201 
202         // get XTextFieldsSupplier, XBookmarksSupplier interfaces
203         XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier)
204             UnoRuntime.queryInterface(XTextFieldsSupplier.class,
205                                       xTemplateComponent);
206         XBookmarksSupplier xBookmarksSupplier = (XBookmarksSupplier)
207             UnoRuntime.queryInterface(XBookmarksSupplier.class, xTemplateComponent);
208 
209         // access the TextFields and the TextFieldMasters collections
210         XNameAccess xNamedFieldMasters = xTextFieldsSupplier.getTextFieldMasters();
211         XEnumerationAccess xEnumeratedFields = xTextFieldsSupplier.getTextFields();
212 
213         // iterate over hashtable and insert values into field masters
214         java.util.Enumeration keys = recipient.keys();
215         while(keys.hasMoreElements()) {
216             // get column name
217             String key = (String)keys.nextElement();
218 
219             // access corresponding field master
220             Object fieldMaster = xNamedFieldMasters.getByName(
221                 "com.sun.star.text.fieldmaster.User." + key);
222 
223             // query the XPropertySet interface, we need to set the Content property
224             XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(
225                 XPropertySet.class, fieldMaster);
226 
227             // insert the column value into field master
228             xPropertySet.setPropertyValue("Content", recipient.get(key));
229         }
230         // afterwards we must refresh the textfields collection
231         XRefreshable xRefreshable = (XRefreshable)UnoRuntime.queryInterface(
232             XRefreshable.class, xEnumeratedFields);
233         xRefreshable.refresh();
234 
235         // accessing the Bookmarks collection of the document
236         XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks();
237 
238         // find the bookmark named "Subscription"
239         Object bookmark = xNamedBookmarks.getByName("Subscription");
240         // we need its XTextRange which is available from getAnchor(),
241         // so query for XTextContent
242         XTextContent xBookmarkContent = (XTextContent)UnoRuntime.queryInterface(
243             XTextContent.class, bookmark);
244         // get the anchor of the bookmark (its XTextRange)
245         XTextRange xBookmarkRange = xBookmarkContent.getAnchor();
246         // set string at the bookmark position
247         xBookmarkRange.setString("subscription for the Manatee Journal");
248 
249     }
250 
251     /** Sample for document changes, starting at the current view cursor position
252      *  The sample changes the paragraph style and the character style at the
253      *  current view cursor selection Open the sample file ViewCursorExampleFile,
254      *  select some text and run the example.
255      *  The current paragraph will be set to Quotations paragraph style.
256      *  The selected text will be set to Quotation character style.
257      */
viewCursorExample()258     private void viewCursorExample() throws java.lang.Exception {
259         // get the remote service manager
260         mxRemoteServiceManager = this.getRemoteServiceManager();
261         // get the Desktop service
262         Object desktop = mxRemoteServiceManager.createInstanceWithContext(
263             "com.sun.star.frame.Desktop", mxRemoteContext);
264         // query its XDesktop interface, we need the current component
265         XDesktop xDesktop = (XDesktop)UnoRuntime.queryInterface(
266             XDesktop.class, desktop);
267         // retrieve the current component and access the controller
268         XComponent xCurrentComponent = xDesktop.getCurrentComponent();
269         XModel xModel = (XModel)UnoRuntime.queryInterface(XModel.class,
270                                                           xCurrentComponent);
271         XController xController = xModel.getCurrentController();
272         // the controller gives us the TextViewCursor
273         XTextViewCursorSupplier xViewCursorSupplier =
274             (XTextViewCursorSupplier)UnoRuntime.queryInterface(
275                 XTextViewCursorSupplier.class, xController);
276         XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor();
277 
278         // query its XPropertySet interface, we want to set character and paragraph
279         // properties
280         XPropertySet xCursorPropertySet = (XPropertySet)UnoRuntime.queryInterface(
281             XPropertySet.class, xViewCursor);
282         // set the appropriate properties for character and paragraph style
283         xCursorPropertySet.setPropertyValue("CharStyleName", "Quotation");
284         xCursorPropertySet.setPropertyValue("ParaStyleName", "Quotations");
285         // print the current page number
286         XPageCursor xPageCursor = (XPageCursor)UnoRuntime.queryInterface(
287             XPageCursor.class, xViewCursor);
288         System.out.println("The current page number is " + xPageCursor.getPage());
289         // the model cursor is much more powerful, so
290         // we create a model cursor at the current view cursor position with the
291         // following steps:
292         // get the Text service from the TextViewCursor, it is an XTextRange:
293          XText xDocumentText = xViewCursor.getText();
294         // create a model cursor from the viewcursor
295         XTextCursor xModelCursor = xDocumentText.createTextCursorByRange(
296             xViewCursor.getStart());
297         // now we could query XWordCursor, XSentenceCursor and XParagraphCursor
298         // or XDocumentInsertable, XSortable or XContentEnumerationAccess
299         // and work with the properties of com.sun.star.text.TextCursor
300         // in this case we just go to the end of the paragraph and add some text.
301         XParagraphCursor xParagraphCursor = (XParagraphCursor)
302             UnoRuntime.queryInterface(XParagraphCursor.class, xModelCursor);
303         // goto the end of the paragraph
304         xParagraphCursor.gotoEndOfParagraph(false);
305         xParagraphCursor.setString(" ***** Fin de semana! ******");
306     }
307 
308 
309     /** Sample for the various editing facilities described in the
310      * developer's manual
311      */
editingExample()312     private void editingExample () throws java.lang.Exception {
313         // create empty swriter document
314         XComponent xEmptyWriterComponent = newDocComponent("swriter");
315         // query its XTextDocument interface to get the text
316         mxDoc = (XTextDocument)UnoRuntime.queryInterface(
317             XTextDocument.class, xEmptyWriterComponent);
318 
319         // get a reference to the body text of the document
320         mxDocText = mxDoc.getText();
321 
322         // Get a reference to the document's property set. This contains document
323         // information like the current word count
324         mxDocProps = (XPropertySet) UnoRuntime.queryInterface(
325             XPropertySet.class, mxDoc );
326 
327         // Simple text insertion example
328         BodyTextExample ();
329         // Example using text ranges to insert strings at the beginning or end
330         // of a text range
331         TextRangeExample ();
332         // Create a document cursor and remember it, it will be used in most
333         // of the following examples
334         mxDocCursor = mxDocText.createTextCursor();
335         // Demonstrate some of the different cursor types (word, sentence)
336         TextCursorExample ();
337 
338         // Access the text document's multi service factory, which we will need
339         // for most of the following examples
340         mxDocFactory = (XMultiServiceFactory) UnoRuntime.queryInterface(
341             XMultiServiceFactory.class, mxDoc );
342 
343         // Examples of text fields, dependent text fields and field masters
344         TextFieldExample ();
345 
346         // Example of using an XEnumerationAccess to iterate over paragraphs and
347         // set properties of each paragraph as we do so
348         ParagraphExample ();
349 
350         // Example of creating and manipulating a text frame
351         TextFrameExample ();
352 
353         // Example of creating and manipulating a text table, text table rows
354         // and text table cells get a new random generator
355         maRandom = new Random();
356         TextTableExample ();
357 
358         // Example of creating, inserting and manipulating text sections, as
359         // well as an example of how to refresh the document
360         TextSectionExample ();
361 
362         // Example of creating a text section over a block of text and formatting
363         // the text section into columns, as well as how to insert an empty
364         // paragraph using the XRelativeTextContentInsert
365         TextColumnsExample ();
366 
367         // Example of creating the NumberingRules service and adjusting
368         // NumberingTypes and NumberingLevels
369         NumberingExample ();
370 
371         // Example of how to use the XStyleFamiliesSupplier interface of the
372         // document and how to create, insert and apply styles
373         StylesExample ();
374         IndexExample ();
375 
376         // Example of how to create and manipulate reference marks and GetReference
377         // text fields
378         ReferenceExample ();
379 
380         // Example of how to create and insert Footnotes and how to use the
381         // XFootnotesSupplier interface of the document
382         FootnoteExample ();
383 
384         // This method demonstrates how to create shapes from the document factory
385         // and how to access the draw page of the document using the
386         // XDrawPageSupplier interface
387         DrawPageExample ();
388 
389         mxFactory = (XMultiServiceFactory)UnoRuntime.queryInterface(
390             XMultiServiceFactory.class, mxRemoteServiceManager);
391         // This example demonstrates the use of the AutoTextContainer,
392         // AutoTextGroup and AutoTextEntry services and shows how to create,
393         // insert and modify auto text blocks
394         AutoTextExample ();
395     }
396 
storePrintExample()397     protected void storePrintExample() throws java.lang.Exception {
398         // get the remote service manager
399         mxRemoteServiceManager = this.getRemoteServiceManager();
400         // retrieve the Desktop object, we need its XComponentLoader
401         Object desktop = mxRemoteServiceManager.createInstanceWithContext(
402             "com.sun.star.frame.Desktop", mxRemoteContext);
403         XComponentLoader xComponentLoader = (XComponentLoader)
404             UnoRuntime.queryInterface(XComponentLoader.class, desktop);
405         PropertyValue[] loadProps = new PropertyValue[0];
406 
407         java.io.File sourceFile = new java.io.File("PrintDemo.odt");
408         StringBuffer sLoadFileUrl = new StringBuffer("file:///");
409         sLoadFileUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
410 
411         XComponent xDoc = xComponentLoader.loadComponentFromURL(
412             sLoadFileUrl.toString(), "_blank", 0, loadProps);
413 
414         if ( xDoc != null ) {
415             sourceFile = new java.io.File(sOutputDir);
416             StringBuffer sStoreFileUrl = new StringBuffer();
417             sStoreFileUrl.append(sourceFile.toURL().toString());
418             sStoreFileUrl.append("somepopularfileformat.doc");
419 
420             storeDocComponent(xDoc, sStoreFileUrl.toString() );
421             printDocComponent(xDoc);
422         }
423     }
424 
getRemoteServiceManager()425     private XMultiComponentFactory getRemoteServiceManager()
426         throws java.lang.Exception
427     {
428         if (mxRemoteContext == null && mxRemoteServiceManager == null) {
429             // get the remote office context. If necessary a new office
430             // process is started
431             mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
432             System.out.println("Connected to a running office ...");
433             mxRemoteServiceManager = mxRemoteContext.getServiceManager();
434         }
435         return mxRemoteServiceManager;
436     }
437 
newDocComponent(String docType)438     protected XComponent newDocComponent(String docType)
439         throws java.lang.Exception
440     {
441         String loadUrl = "private:factory/" + docType;
442         mxRemoteServiceManager = this.getRemoteServiceManager();
443         Object desktop = mxRemoteServiceManager.createInstanceWithContext(
444             "com.sun.star.frame.Desktop", mxRemoteContext);
445         XComponentLoader xComponentLoader = (XComponentLoader)
446             UnoRuntime.queryInterface(XComponentLoader.class, desktop);
447         PropertyValue[] loadProps = new PropertyValue[0];
448         return xComponentLoader.loadComponentFromURL(loadUrl, "_blank",
449                                                      0, loadProps);
450     }
451 
452     /** Load a document as template
453      */
newDocComponentFromTemplate(String loadUrl)454     protected XComponent newDocComponentFromTemplate(String loadUrl)
455         throws java.lang.Exception
456     {
457         // get the remote service manager
458         mxRemoteServiceManager = this.getRemoteServiceManager();
459         // retrieve the Desktop object, we need its XComponentLoader
460         Object desktop = mxRemoteServiceManager.createInstanceWithContext(
461             "com.sun.star.frame.Desktop", mxRemoteContext);
462         XComponentLoader xComponentLoader = (XComponentLoader)
463             UnoRuntime.queryInterface(XComponentLoader.class, desktop);
464 
465         // define load properties according to com.sun.star.document.MediaDescriptor
466         // the boolean property AsTemplate tells the office to create a new document
467         // from the given file
468         PropertyValue[] loadProps = new PropertyValue[1];
469         loadProps[0] = new PropertyValue();
470         loadProps[0].Name = "AsTemplate";
471         loadProps[0].Value = new Boolean(true);
472         // load
473         return xComponentLoader.loadComponentFromURL(loadUrl, "_blank",
474                                                      0, loadProps);
475     }
476 
477     /** Load a document with arguments (text purposes)
478      */
storeDocComponent(XComponent xDoc, String storeUrl)479     protected void storeDocComponent(XComponent xDoc, String storeUrl)
480         throws java.lang.Exception
481     {
482 
483         XStorable xStorable = (XStorable)UnoRuntime.queryInterface(
484             XStorable.class, xDoc);
485         PropertyValue[] storeProps = new PropertyValue[1];
486         storeProps[0] = new PropertyValue();
487         storeProps[0].Name = "FilterName";
488         storeProps[0].Value = "MS Word 97";
489 
490         System.out.println("... store \"PrintDemo.odt\" to \"" + storeUrl + "\".");
491         xStorable.storeAsURL(storeUrl, storeProps);
492     }
493 
printDocComponent(XComponent xDoc)494     protected void printDocComponent(XComponent xDoc) throws java.lang.Exception {
495         XPrintable xPrintable = (XPrintable)UnoRuntime.queryInterface(
496             XPrintable.class, xDoc);
497         PropertyValue[] printerDesc = new PropertyValue[1];
498         printerDesc[0] = new PropertyValue();
499         printerDesc[0].Name = "Name";
500         printerDesc[0].Value = aPrinterName;
501 
502         xPrintable.setPrinter(printerDesc);
503 
504         PropertyValue[] printOpts = new PropertyValue[1];
505         printOpts[0] = new PropertyValue();
506         printOpts[0].Name = "Pages";
507         printOpts[0].Value = "1";
508 
509         xPrintable.print(printOpts);
510     }
511 
512     // Setting the whole text of a document as one string
BodyTextExample()513     protected void BodyTextExample ()
514     {
515         // Body Text and TextDocument example
516         try
517         {
518             // demonstrate simple text insertion
519             mxDocText.setString ( "This is the new body text of the document."
520                                   + "\n\nThis is on the second line.\n\n" );
521         }
522         catch ( Exception e )
523         {
524             e.printStackTrace();
525         }
526     }
527 
528     // Adding a string at the end or the beginning of text
TextRangeExample()529     protected void TextRangeExample ()
530     {
531         try
532         {
533             // Get a text range referring to the beginning of the text document
534             XTextRange xStart = mxDocText.getStart();
535             // use setString to insert text at the beginning
536             xStart.setString ( "This is text inserted at the beginning.\n\n" );
537             // Get a text range referring to the end of the text document
538             XTextRange xEnd = mxDocText.getEnd();
539             // use setString to insert text at the end
540             xEnd.setString ( "This is text inserted at the end.\n\n" );
541         }
542         catch ( Exception e )
543         {
544             e.printStackTrace();
545         }
546     }
547 
548     /** moving a text cursor, selecting text and overwriting it
549     */
TextCursorExample()550     protected void TextCursorExample ()
551     {
552         try
553         {
554             // First, get the XSentenceCursor interface of our text cursor
555             XSentenceCursor xSentenceCursor = (XSentenceCursor)
556                 UnoRuntime.queryInterface(XSentenceCursor.class, mxDocCursor );
557             // Goto the next cursor, without selecting it
558             xSentenceCursor.gotoNextSentence( false );
559             // Get the XWordCursor interface of our text cursor
560             XWordCursor xWordCursor = (XWordCursor) UnoRuntime.queryInterface(
561                 XWordCursor.class, mxDocCursor );
562             // Skip the first four words of this sentence and select the fifth
563             xWordCursor.gotoNextWord( false );
564             xWordCursor.gotoNextWord( false );
565             xWordCursor.gotoNextWord( false );
566             xWordCursor.gotoNextWord( false );
567             xWordCursor.gotoNextWord( true );
568             // Use the XSimpleText interface to insert a word at the current cursor
569             // location, over-writing the current selection (the fifth word
570             // selected above)
571             mxDocText.insertString ( xWordCursor, "old ", true );
572 
573             // Access the property set of the cursor, and set the currently
574             // selected text (which is the string we just inserted) to be bold
575             XPropertySet xCursorProps = (XPropertySet) UnoRuntime.queryInterface(
576                 XPropertySet.class, mxDocCursor );
577             xCursorProps.setPropertyValue ( "CharWeight",
578                              new Float(com.sun.star.awt.FontWeight.BOLD) );
579 
580             // replace the '.' at the end of the sentence with a new string
581             xSentenceCursor.gotoEndOfSentence( false );
582             xWordCursor.gotoPreviousWord( true );
583             mxDocText.insertString (xWordCursor,
584                                     ", which has been changed with text cursors!",
585                                     true);
586         }
587         catch ( Exception e )
588         {
589             e.printStackTrace();
590         }
591     }
592 
593     /** This method inserts both a date field and a user field containing the
594      * number '42'
595      */
TextFieldExample()596     protected void TextFieldExample ()
597     {
598         try
599         {
600             // Use the text document's factory to create a DateTime text field,
601             // and access its XTextField interface
602             XTextField xDateField = (XTextField) UnoRuntime.queryInterface (
603                 XTextField.class, mxDocFactory.createInstance (
604                     "com.sun.star.text.TextField.DateTime" ) );
605 
606             // Insert it at the end of the document
607             mxDocText.insertTextContent ( mxDocText.getEnd(), xDateField, false );
608 
609             // Use the text document's factory to create a user text field,
610             // and access its XDependentTextField interface
611             XDependentTextField xUserField =
612                 (XDependentTextField) UnoRuntime.queryInterface (
613                     XDependentTextField.class, mxDocFactory.createInstance (
614                         "com.sun.star.text.TextField.User" ) );
615 
616             // Create a fieldmaster for our newly created User Text field, and
617             // access its XPropertySet interface
618             XPropertySet xMasterPropSet = (XPropertySet)UnoRuntime.queryInterface(
619                 XPropertySet.class, mxDocFactory.createInstance (
620                     "com.sun.star.text.fieldmaster.User" ) );
621 
622             // Set the name and value of the FieldMaster
623             xMasterPropSet.setPropertyValue ( "Name", "UserEmperor" );
624             xMasterPropSet.setPropertyValue ( "Value", new Integer ( 42 ) );
625 
626             // Attach the field master to the user field
627             xUserField.attachTextFieldMaster ( xMasterPropSet );
628 
629             // Move the cursor to the end of the document
630             mxDocCursor.gotoEnd( false );
631             // insert a paragraph break using the XSimpleText interface
632             mxDocText.insertControlCharacter (
633                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
634 
635             // Insert the user field at the end of the document
636             mxDocText.insertTextContent ( mxDocText.getEnd(), xUserField, false );
637         }
638         catch ( Exception e )
639         {
640             e.printStackTrace();
641         }
642     }
643 
644     /** This method demonstrates how to iterate over paragraphs
645      */
ParagraphExample()646     protected void ParagraphExample ()
647     {
648         try
649         {
650             // The service 'com.sun.star.text.Text' supports the XEnumerationAccess
651             // interface to provide an enumeration of the paragraphs contained by
652             // the text the service refers to.
653 
654             // Here, we access this interface
655             XEnumerationAccess xParaAccess = (XEnumerationAccess)
656                 UnoRuntime.queryInterface(XEnumerationAccess.class, mxDocText );
657             // Call the XEnumerationAccess's only method to access the actual
658             // Enumeration
659             XEnumeration xParaEnum = xParaAccess.createEnumeration();
660 
661             // While there are paragraphs, do things to them
662             while ( xParaEnum.hasMoreElements() )
663             {
664                 // Get a reference to the next paragraphs XServiceInfo interface.
665                 // TextTables are also part of this enumeration access, so we ask
666                 // the element if it is a TextTable, if it doesn't support the
667                 // com.sun.star.text.TextTable service, then it is safe to assume
668                 // that it really is a paragraph
669                 XServiceInfo xInfo = (XServiceInfo) UnoRuntime.queryInterface(
670                     XServiceInfo.class, xParaEnum.nextElement() );
671                 if ( !xInfo.supportsService ( "com.sun.star.text.TextTable" ) )
672                 {
673                     // Access the paragraph's property set...the properties in this
674                     // property set are listed in:
675                     // com.sun.star.style.ParagraphProperties
676                     XPropertySet xSet = (XPropertySet) UnoRuntime.queryInterface(
677                         XPropertySet.class, xInfo );
678                     // Set the justification to be center justified
679                     xSet.setPropertyValue ( "ParaAdjust",
680                              com.sun.star.style.ParagraphAdjust.CENTER );
681                 }
682             }
683         }
684         catch ( Exception e )
685         {
686             e.printStackTrace();
687         }
688     }
689 
690     /** This method returns a random double which isn't too high or too low
691      */
getRandomDouble()692     protected double getRandomDouble ()
693     {
694         return ( ( maRandom.nextInt() % 1000 ) * maRandom.nextDouble () );
695     }
696 
697     /** This method sets the text color of the cell referred to by sCellName to
698         white and inserts the string sText in it
699      */
insertIntoCell(String sCellName, String sText, XTextTable xTable)700     protected static void insertIntoCell(String sCellName, String sText,
701                                          XTextTable xTable)
702     {
703         // Access the XText interface of the cell referred to by sCellName
704         XText xCellText = (XText) UnoRuntime.queryInterface(
705             XText.class, xTable.getCellByName ( sCellName ) );
706 
707         // create a text cursor from the cells XText interface
708         XTextCursor xCellCursor = xCellText.createTextCursor();
709         // Get the property set of the cell's TextCursor
710         XPropertySet xCellCursorProps = (XPropertySet)UnoRuntime.queryInterface(
711             XPropertySet.class, xCellCursor );
712 
713         try
714         {
715             // Set the color of the text to white
716             xCellCursorProps.setPropertyValue( "CharColor", new Integer(16777215));
717         }
718         catch ( Exception e)
719         {
720             e.printStackTrace();
721         }
722         // Set the text in the cell to sText
723         xCellText.setString( sText );
724     }
725 
726     /** This method shows how to create and insert a text table, as well as insert
727 		text and formula into the cells of the table
728      */
TextTableExample()729     protected void TextTableExample ()
730     {
731         try
732         {
733             // Create a new table from the document's factory
734             XTextTable xTable = (XTextTable) UnoRuntime.queryInterface(
735                 XTextTable.class, mxDocFactory .createInstance(
736                     "com.sun.star.text.TextTable" ) );
737 
738             // Specify that we want the table to have 4 rows and 4 columns
739             xTable.initialize( 4, 4 );
740 
741             // Insert the table into the document
742             mxDocText.insertTextContent( mxDocCursor, xTable, false);
743             // Get an XIndexAccess of the table rows
744             XIndexAccess xRows = xTable.getRows();
745 
746             // Access the property set of the first row (properties listed in
747             // service description: com.sun.star.text.TextTableRow)
748             XPropertySet xRow = (XPropertySet) UnoRuntime.queryInterface(
749                 XPropertySet.class, xRows.getByIndex ( 0 ) );
750             // If BackTransparant is false, then the background color is visible
751             xRow.setPropertyValue( "BackTransparent", new Boolean(false));
752             // Specify the color of the background to be dark blue
753             xRow.setPropertyValue( "BackColor", new Integer(6710932));
754 
755             // Access the property set of the whole table
756             XPropertySet xTableProps = (XPropertySet)UnoRuntime.queryInterface(
757                 XPropertySet.class, xTable );
758             // We want visible background colors
759             xTableProps.setPropertyValue( "BackTransparent", new Boolean(false));
760             // Set the background color to light blue
761             xTableProps.setPropertyValue( "BackColor", new Integer(13421823));
762 
763             // set the text (and text color) of all the cells in the first row
764             // of the table
765             insertIntoCell( "A1", "First Column", xTable );
766             insertIntoCell( "B1", "Second Column", xTable );
767             insertIntoCell( "C1", "Third Column", xTable );
768             insertIntoCell( "D1", "Results", xTable );
769 
770             // Insert random numbers into the first this three cells of each
771             // remaining row
772             xTable.getCellByName( "A2" ).setValue( getRandomDouble() );
773             xTable.getCellByName( "B2" ).setValue( getRandomDouble() );
774             xTable.getCellByName( "C2" ).setValue( getRandomDouble() );
775 
776             xTable.getCellByName( "A3" ).setValue( getRandomDouble() );
777             xTable.getCellByName( "B3" ).setValue( getRandomDouble() );
778             xTable.getCellByName( "C3" ).setValue( getRandomDouble() );
779 
780             xTable.getCellByName( "A4" ).setValue( getRandomDouble() );
781             xTable.getCellByName( "B4" ).setValue( getRandomDouble() );
782             xTable.getCellByName( "C4" ).setValue( getRandomDouble() );
783 
784             // Set the last cell in each row to be a formula that calculates
785             // the sum of the first three cells
786             xTable.getCellByName( "D2" ).setFormula( "sum <A2:C2>" );
787             xTable.getCellByName( "D3" ).setFormula( "sum <A3:C3>" );
788             xTable.getCellByName( "D4" ).setFormula( "sum <A4:C4>" );
789         }
790         catch (Exception e)
791         {
792             e.printStackTrace();
793         }
794     }
795     /** This method shows how to create and manipulate text frames
796      */
TextFrameExample()797     protected void TextFrameExample ()
798     {
799         try
800         {
801             // Use the document's factory to create a new text frame and
802             // immediately access its XTextFrame interface
803             XTextFrame xFrame = (XTextFrame) UnoRuntime.queryInterface (
804                 XTextFrame.class, mxDocFactory.createInstance (
805                     "com.sun.star.text.TextFrame" ) );
806 
807             // Access the XShape interface of the TextFrame
808             XShape xShape = (XShape)UnoRuntime.queryInterface(XShape.class, xFrame);
809             // Access the XPropertySet interface of the TextFrame
810             XPropertySet xFrameProps = (XPropertySet)UnoRuntime.queryInterface(
811                 XPropertySet.class, xFrame );
812 
813             // Set the size of the new Text Frame using the XShape's 'setSize'
814             // method
815             Size aSize = new Size();
816             aSize.Height = 400;
817             aSize.Width = 15000;
818             xShape.setSize(aSize);
819             // Set the AnchorType to
820             // com.sun.star.text.TextContentAnchorType.AS_CHARACTER
821             xFrameProps.setPropertyValue( "AnchorType",
822                                           TextContentAnchorType.AS_CHARACTER );
823             // Go to the end of the text document
824             mxDocCursor.gotoEnd( false );
825             // Insert a new paragraph
826             mxDocText.insertControlCharacter (
827                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
828             // Then insert the new frame
829             mxDocText.insertTextContent(mxDocCursor, xFrame, false);
830 
831             // Access the XText interface of the text contained within the frame
832             XText xFrameText = xFrame.getText();
833             // Create a TextCursor over the frame's contents
834             XTextCursor xFrameCursor = xFrameText.createTextCursor();
835             // Insert some text into the frame
836             xFrameText.insertString(
837                 xFrameCursor, "The first line in the newly created text frame.",
838                 false );
839             xFrameText.insertString(
840                 xFrameCursor, "\nThe second line in the new text frame.", false );
841             // Insert a paragraph break into the document (not the frame)
842             mxDocText.insertControlCharacter (
843                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
844         }
845         catch (Exception e)
846         {
847             e.printStackTrace();
848         }
849     }
850 
851     /** This example demonstrates the use of the AutoTextContainer, AutoTextGroup
852         and AutoTextEntry services and shows how to create, insert and modify
853         auto text blocks
854      */
AutoTextExample()855     protected void AutoTextExample ()
856     {
857         try
858         {
859             // Go to the end of the document
860             mxDocCursor.gotoEnd( false );
861             // Insert two paragraphs
862             mxDocText.insertControlCharacter ( mxDocCursor,
863                           ControlCharacter.PARAGRAPH_BREAK, false );
864             mxDocText.insertControlCharacter ( mxDocCursor,
865                           ControlCharacter.PARAGRAPH_BREAK, false );
866             // Position the cursor in the second paragraph
867             XParagraphCursor xParaCursor = (XParagraphCursor)
868                 UnoRuntime.queryInterface(XParagraphCursor.class, mxDocCursor );
869             xParaCursor.gotoPreviousParagraph ( false );
870 
871             // Get an XNameAccess interface to all auto text groups from the
872             // document factory
873             XNameAccess xContainer = (XNameAccess) UnoRuntime.queryInterface(
874                 XNameAccess.class, mxFactory.createInstance (
875                     "com.sun.star.text.AutoTextContainer" ) );
876 
877             // Create a new table at the document factory
878             XTextTable xTable = (XTextTable) UnoRuntime.queryInterface(
879                 XTextTable.class, mxDocFactory .createInstance(
880                     "com.sun.star.text.TextTable" ) );
881 
882             // Store the names of all auto text groups in an array of strings
883             String[] aGroupNames = xContainer.getElementNames();
884 
885             // Make sure we have at least one group name
886             if ( aGroupNames.length > 0 )
887             {
888                 // initialize the table to have a row for every autotext group
889                 // in a single column + one additional row for a header
890                 xTable.initialize( aGroupNames.length+1,1);
891 
892                 // Access the XPropertySet of the table
893                 XPropertySet xTableProps = (XPropertySet)UnoRuntime.queryInterface(
894                     XPropertySet.class, xTable );
895 
896                 // We want a visible background
897                 xTableProps.setPropertyValue( "BackTransparent",
898                                               new Boolean(false));
899 
900                 // We want the background to be light blue
901                 xTableProps.setPropertyValue( "BackColor", new Integer(13421823));
902 
903                 // Insert the table into the document
904                 mxDocText.insertTextContent( mxDocCursor, xTable, false);
905 
906                 // Get an XIndexAccess to all table rows
907                 XIndexAccess xRows = xTable.getRows();
908 
909                 // Get the first row in the table
910                 XPropertySet xRow = (XPropertySet) UnoRuntime.queryInterface(
911                     XPropertySet.class, xRows.getByIndex ( 0 ) );
912 
913                 // We want the background of the first row to be visible too
914                 xRow.setPropertyValue( "BackTransparent", new Boolean(false));
915 
916                 // And let's make it dark blue
917                 xRow.setPropertyValue( "BackColor", new Integer(6710932));
918 
919                 // Put a description of the table contents into the first cell
920                 insertIntoCell( "A1", "AutoText Groups", xTable);
921 
922                 // Create a table cursor pointing at the second cell in the first
923                 // column
924                 XTextTableCursor xTableCursor = xTable.createCursorByCellName("A2");
925 
926                 // Loop over the group names
927                 for ( int i = 0 ; i < aGroupNames.length ; i ++ )
928                 {
929                     // Get the name of the current cell
930                     String sCellName = xTableCursor.getRangeName ();
931 
932                     // Get the XText interface of the current cell
933                     XText xCellText = (XText) UnoRuntime.queryInterface (
934                         XText.class, xTable.getCellByName ( sCellName ) );
935 
936                     // Set the cell contents of the current cell to be
937                     //the name of the of an autotext group
938                     xCellText.setString ( aGroupNames[i] );
939 
940                     // Access the autotext group with this name
941                     XAutoTextGroup xGroup = (XAutoTextGroup)
942                         UnoRuntime.queryInterface (XAutoTextGroup.class,
943                                        xContainer.getByName(aGroupNames[i]));
944 
945                     // Get the titles of each autotext block in this group
946                     String [] aBlockNames = xGroup.getTitles();
947 
948                     // Make sure that the autotext group contains at least one block
949                     if ( aBlockNames.length > 0 )
950                     {
951                         // Split the current cell vertically into two separate cells
952                         xTableCursor.splitRange ( (short) 1, false );
953 
954                         // Put the cursor in the newly created right hand cell
955                         // and select it
956                         xTableCursor.goRight ( (short) 1, false );
957 
958                         // Split this cell horizontally to make a separate cell
959                         // for each Autotext block
960                         if ( ( aBlockNames.length -1 ) > 0 )
961                             xTableCursor.splitRange (
962                                 (short) (aBlockNames.length - 1), true );
963 
964                         // loop over the block names
965                         for ( int j = 0 ; j < aBlockNames.length ; j ++ )
966                         {
967                             // Get the XText interface of the current cell
968                             xCellText = (XText) UnoRuntime.queryInterface (
969                                 XText.class, xTable.getCellByName (
970                                     xTableCursor.getRangeName() ) );
971 
972                             // Set the text contents of the current cell to the
973                             // title of an Autotext block
974                             xCellText.setString ( aBlockNames[j] );
975 
976                             // Move the cursor down one cell
977                             xTableCursor.goDown( (short)1, false);
978                         }
979                     }
980                     // Go back to the cell we originally split
981                     xTableCursor.gotoCellByName ( sCellName, false );
982 
983                                     // Go down one cell
984                     xTableCursor.goDown( (short)1, false);
985                 }
986 
987                 XAutoTextGroup xGroup;
988                 String [] aBlockNames;
989 
990                 // Add a depth so that we only generate 200 numbers before giving up
991                 // on finding a random autotext group that contains autotext blocks
992                 int nDepth = 0;
993                 do
994                 {
995                     // Generate a random, positive number which is lower than
996                     // the number of autotext groups
997                     int nRandom = Math.abs ( maRandom.nextInt() %
998                                              aGroupNames.length );
999 
1000                     // Get the autotext group at this name
1001                     xGroup 	= ( XAutoTextGroup ) UnoRuntime.queryInterface (
1002                         XAutoTextGroup.class, xContainer.getByName (
1003                             aGroupNames[ nRandom ] ) );
1004 
1005                     // Fill our string array with the names of all the blocks in
1006                     // this group
1007                     aBlockNames = xGroup.getElementNames();
1008 
1009                     // increment our depth counter
1010                     ++nDepth;
1011                 }
1012                 while ( nDepth < 200 && aBlockNames.length == 0 );
1013                 // If we managed to find a group containing blocks...
1014                 if ( aBlockNames.length > 0 )
1015                 {
1016                     // Pick a random block in this group and get its
1017                     // XAutoTextEntry interface
1018                     int nRandom = Math.abs ( maRandom.nextInt()
1019                                              % aBlockNames.length );
1020                     XAutoTextEntry xEntry = ( XAutoTextEntry )
1021                         UnoRuntime.queryInterface (
1022                             XAutoTextEntry.class, xGroup.getByName (
1023                                 aBlockNames[ nRandom ] ) );
1024                     // insert the modified autotext block at the end of the document
1025                     xEntry.applyTo ( mxDocCursor );
1026 
1027                     // Get the titles of all text blocks in this AutoText group
1028                     String [] aBlockTitles = xGroup.getTitles();
1029 
1030                     // Get the XNamed interface of the autotext group
1031                     XNamed xGroupNamed = ( XNamed ) UnoRuntime.queryInterface (
1032                         XNamed.class, xGroup );
1033 
1034                     // Output the short cut and title of the random block
1035                     // and the name of the group it's from
1036                     System.out.println ( "Inserted the Autotext '" +
1037                                          aBlockTitles[nRandom]
1038                                          + "', shortcut '" + aBlockNames[nRandom]
1039                                          + "' from group '"
1040                                          + xGroupNamed.getName());
1041                 }
1042             }
1043 
1044             // Go to the end of the document
1045             mxDocCursor.gotoEnd( false );
1046             // Insert new paragraph
1047             mxDocText.insertControlCharacter (
1048                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1049 
1050             // Position cursor in new paragraph
1051             xParaCursor.gotoPreviousParagraph ( false );
1052 
1053             // Insert a string in the new paragraph
1054             mxDocText.insertString ( mxDocCursor,
1055                                      "Some text for a new autotext block", false );
1056 
1057             // Go to the end of the document
1058             mxDocCursor.gotoEnd( false );
1059         }
1060         catch (Exception e)
1061         {
1062             e.printStackTrace();
1063         }
1064     }
1065 
1066     /** This method demonstrates how to insert indexes and index marks
1067      */
IndexExample()1068     protected void IndexExample ()
1069     {
1070         try
1071         {
1072             // Go to the end of the document
1073             mxDocCursor.gotoEnd( false );
1074             // Insert a new paragraph and position the cursor in it
1075             mxDocText.insertControlCharacter ( mxDocCursor,
1076                           ControlCharacter.PARAGRAPH_BREAK, false );
1077             XParagraphCursor xParaCursor = (XParagraphCursor)
1078                 UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1079             xParaCursor.gotoPreviousParagraph ( false );
1080 
1081             // Create a new ContentIndexMark and get its XPropertySet interface
1082             XPropertySet xEntry = (XPropertySet)UnoRuntime.queryInterface(
1083                 XPropertySet.class,
1084                 mxDocFactory.createInstance("com.sun.star.text.ContentIndexMark"));
1085 
1086             // Set the text to be displayed in the index
1087             xEntry.setPropertyValue(
1088                 "AlternativeText", "Big dogs! Falling on my head!");
1089 
1090             // The Level property _must_ be set
1091             xEntry.setPropertyValue ( "Level", new Short ( (short) 1 ) );
1092 
1093             // Create a ContentIndex and access its XPropertySet interface
1094             XPropertySet xIndex = (XPropertySet) UnoRuntime.queryInterface(
1095                 XPropertySet.class,
1096                 mxDocFactory.createInstance ( "com.sun.star.text.ContentIndex" ) );
1097 
1098             // Again, the Level property _must_ be set
1099             xIndex.setPropertyValue ( "Level", new Short ( (short) 10 ) );
1100 
1101             // Access the XTextContent interfaces of both the Index and the
1102             // IndexMark
1103             XTextContent xIndexContent = (XTextContent) UnoRuntime.queryInterface(
1104                 XTextContent.class, xIndex );
1105             XTextContent xEntryContent = (XTextContent) UnoRuntime.queryInterface(
1106                 XTextContent.class, xEntry );
1107 
1108             // Insert both in the document
1109             mxDocText.insertTextContent ( mxDocCursor, xEntryContent, false );
1110             mxDocText.insertTextContent ( mxDocCursor, xIndexContent, false );
1111 
1112             // Get the XDocumentIndex interface of the Index
1113             XDocumentIndex xDocIndex = (XDocumentIndex) UnoRuntime.queryInterface(
1114                 XDocumentIndex.class, xIndex );
1115 
1116             // And call its update method
1117             xDocIndex.update();
1118         }
1119         catch (Exception e)
1120         {
1121             e.printStackTrace();
1122         }
1123     }
1124 
1125     /** This method demonstrates how to create and insert reference marks, and
1126      *  GetReference Text Fields
1127      */
ReferenceExample()1128     protected void ReferenceExample ()
1129     {
1130         try
1131         {
1132             // Go to the end of the document
1133             mxDocCursor.gotoEnd( false );
1134 
1135             // Insert a paragraph break
1136             mxDocText.insertControlCharacter (
1137                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1138 
1139             // Get the Paragraph cursor
1140             XParagraphCursor xParaCursor = (XParagraphCursor)
1141                 UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1142 
1143             // Move the cursor into the new paragraph
1144             xParaCursor.gotoPreviousParagraph ( false );
1145 
1146             // Create a new ReferenceMark and get its XNamed interface
1147             XNamed xRefMark = (XNamed) UnoRuntime.queryInterface(XNamed.class,
1148                   mxDocFactory.createInstance ("com.sun.star.text.ReferenceMark"));
1149 
1150             // Set the name to TableHeader
1151             xRefMark.setName ( "TableHeader" );
1152 
1153             // Get the TextTablesSupplier interface of the document
1154             XTextTablesSupplier xTableSupplier = ( XTextTablesSupplier )
1155                 UnoRuntime.queryInterface(XTextTablesSupplier.class, mxDoc);
1156 
1157             // Get an XIndexAccess of TextTables
1158             XIndexAccess xTables = (XIndexAccess)UnoRuntime.queryInterface(
1159                 XIndexAccess.class, xTableSupplier.getTextTables());
1160 
1161             // We've only inserted one table, so get the first one from index zero
1162             XTextTable xTable = ( XTextTable ) UnoRuntime.queryInterface (
1163                 XTextTable.class, xTables.getByIndex( 0 ) );
1164 
1165             // Get the first cell from the table
1166             XText xTableText = (XText) UnoRuntime.queryInterface(
1167                 XText.class, xTable.getCellByName ( "A1" ) );
1168 
1169             // Get a text cursor for the first cell
1170             XTextCursor xTableCursor = xTableText.createTextCursor();
1171 
1172             // Get the XTextContent interface of the reference mark so we can
1173             // insert it
1174             XTextContent xContent = ( XTextContent ) UnoRuntime.queryInterface (
1175                 XTextContent.class, xRefMark );
1176 
1177             // Insert the reference mark into the first cell of the table
1178             xTableText.insertTextContent ( xTableCursor, xContent, false );
1179 
1180             // Create a 'GetReference' text field to refer to the reference mark
1181             // we just inserted, and get its XPropertySet interface
1182             XPropertySet xFieldProps = (XPropertySet) UnoRuntime.queryInterface(
1183                 XPropertySet.class, mxDocFactory.createInstance (
1184                     "com.sun.star.text.TextField.GetReference" ) );
1185 
1186             // Get the XReferenceMarksSupplier interface of the document
1187             XReferenceMarksSupplier xRefSupplier = ( XReferenceMarksSupplier )
1188                 UnoRuntime.queryInterface( XReferenceMarksSupplier.class, mxDoc );
1189 
1190             // Get an XNameAccess which refers to all inserted reference marks
1191             XNameAccess xMarks = ( XNameAccess ) UnoRuntime.queryInterface (
1192                 XNameAccess.class, xRefSupplier.getReferenceMarks() );
1193 
1194             // Put the names of each reference mark into an array of strings
1195             String[] aNames = xMarks.getElementNames();
1196 
1197             // Make sure that at least 1 reference mark actually exists
1198             // (well, we just inserted one!)
1199             if ( aNames.length > 0 )
1200             {
1201                 // Output the name of the first reference mark ('TableHeader')
1202                 System.out.println (
1203                     "GetReference text field inserted for ReferenceMark : "
1204                     + aNames[0] );
1205 
1206                 // Set the SourceName of the GetReference text field to
1207                 // 'TableHeader'
1208                 xFieldProps.setPropertyValue ( "SourceName", aNames[0] );
1209 
1210                 // specify that the source is a reference mark (could also be a
1211                 // footnote, bookmark or sequence field )
1212                 xFieldProps.setPropertyValue ( "ReferenceFieldSource",
1213                                 new Short(ReferenceFieldSource.REFERENCE_MARK));
1214 
1215                 // We want the reference displayed as 'above' or 'below'
1216                 xFieldProps.setPropertyValue ( "ReferenceFieldPart",
1217                                 new Short(ReferenceFieldPart.UP_DOWN));
1218 
1219 
1220                 // Get the XTextContent interface of the GetReference text field
1221                 XTextContent xRefContent = (XTextContent) UnoRuntime.queryInterface(
1222                     XTextContent.class, xFieldProps );
1223 
1224                 // Go to the end of the document
1225                 mxDocCursor.gotoEnd( false );
1226 
1227                 // Make some text to precede the reference
1228                 mxDocText.insertString(mxDocText.getEnd(), "The table ", false);
1229 
1230                 // Insert the text field
1231                 mxDocText.insertTextContent(mxDocText.getEnd(), xRefContent, false);
1232 
1233                 // And some text after the reference..
1234                 mxDocText.insertString(mxDocText.getEnd(),
1235                               " contains the sum of some random numbers.", false );
1236 
1237                 // Refresh the document
1238                 XRefreshable xRefresh = (XRefreshable) UnoRuntime.queryInterface(
1239                     XRefreshable.class, mxDoc );
1240                 xRefresh.refresh();
1241             }
1242         }
1243         catch (Exception e)
1244         {
1245             e.printStackTrace();
1246         }
1247     }
1248 
1249     /** This method demonstrates how to create and insert footnotes, and how to
1250         access the XFootnotesSupplier interface of the document
1251      */
FootnoteExample()1252     protected void FootnoteExample ()
1253     {
1254         try
1255         {
1256             // Create a new footnote from the document factory and get its
1257             // XFootnote interface
1258             XFootnote xFootnote = (XFootnote) UnoRuntime.queryInterface(
1259                 XFootnote.class, mxDocFactory.createInstance (
1260                     "com.sun.star.text.Footnote" ) );
1261 
1262             // Set the label to 'Numbers'
1263             xFootnote.setLabel ( "Numbers" );
1264 
1265             // Get the footnotes XTextContent interface so we can...
1266             XTextContent xContent = ( XTextContent ) UnoRuntime.queryInterface (
1267                 XTextContent.class, xFootnote );
1268 
1269             // ...insert it into the document
1270             mxDocText.insertTextContent ( mxDocCursor, xContent, false );
1271 
1272             // Get the XFootnotesSupplier interface of the document
1273             XFootnotesSupplier xFootnoteSupplier = (XFootnotesSupplier)
1274                 UnoRuntime.queryInterface(XFootnotesSupplier.class, mxDoc );
1275 
1276             // Get an XIndexAccess interface to all footnotes
1277             XIndexAccess xFootnotes = ( XIndexAccess ) UnoRuntime.queryInterface (
1278                 XIndexAccess.class, xFootnoteSupplier.getFootnotes() );
1279 
1280             // Get the XFootnote interface to the first footnote inserted ('Numbers')
1281             XFootnote xNumbers = ( XFootnote ) UnoRuntime.queryInterface (
1282                 XFootnote.class, xFootnotes.getByIndex( 0 ) );
1283 
1284             // Get the XSimpleText interface to the Footnote
1285             XSimpleText xSimple = (XSimpleText ) UnoRuntime.queryInterface (
1286                 XSimpleText.class, xNumbers );
1287 
1288             // Create a text cursor for the foot note text
1289             XTextRange xRange = (XTextRange ) UnoRuntime.queryInterface (
1290                 XTextRange.class, xSimple.createTextCursor() );
1291 
1292             // And insert the actual text of the footnote.
1293             xSimple.insertString (
1294                 xRange, "  The numbers were generated by using java.util.Random", false );
1295         }
1296         catch (Exception e)
1297         {
1298             e.printStackTrace();
1299         }
1300     }
1301 
1302     /** This method demonstrates how to create and manipulate shapes, and how to
1303         access the draw page of the document to insert shapes
1304      */
DrawPageExample()1305     protected void DrawPageExample ()
1306     {
1307         try
1308         {
1309             // Go to the end of the document
1310             mxDocCursor.gotoEnd( false );
1311             // Insert two new paragraphs
1312             mxDocText.insertControlCharacter(mxDocCursor,
1313                           ControlCharacter.PARAGRAPH_BREAK, false);
1314             mxDocText.insertControlCharacter(mxDocCursor,
1315                           ControlCharacter.PARAGRAPH_BREAK, false);
1316 
1317             // Get the XParagraphCursor interface of our document cursor
1318             XParagraphCursor xParaCursor = (XParagraphCursor)
1319                 UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1320 
1321             // Position the cursor in the 2nd paragraph
1322             xParaCursor.gotoPreviousParagraph ( false );
1323 
1324             // Create a RectangleShape using the document factory
1325             XShape xRect = (XShape) UnoRuntime.queryInterface(
1326                 XShape.class, mxDocFactory.createInstance (
1327                     "com.sun.star.drawing.RectangleShape" ) );
1328 
1329             // Create an EllipseShape using the document factory
1330             XShape xEllipse = (XShape) UnoRuntime.queryInterface(
1331                 XShape.class, mxDocFactory.createInstance (
1332                     "com.sun.star.drawing.EllipseShape" ) );
1333 
1334             // Set the size of both the ellipse and the rectangle
1335             Size aSize = new Size();
1336             aSize.Height = 4000;
1337             aSize.Width = 10000;
1338             xRect.setSize(aSize);
1339             aSize.Height = 3000;
1340             aSize.Width = 6000;
1341             xEllipse.setSize ( aSize );
1342 
1343             // Set the position of the Rectangle to the right of the ellipse
1344             Point aPoint = new Point();
1345             aPoint.X = 6100;
1346             aPoint.Y = 0;
1347             xRect.setPosition ( aPoint );
1348 
1349             // Get the XPropertySet interfaces of both shapes
1350             XPropertySet xRectProps = (XPropertySet) UnoRuntime.queryInterface(
1351                 XPropertySet.class, xRect );
1352             XPropertySet xEllipseProps = (XPropertySet) UnoRuntime.queryInterface(
1353                 XPropertySet.class, xEllipse );
1354 
1355             // And set the AnchorTypes of both shapes to 'AT_PARAGRAPH'
1356             xRectProps.setPropertyValue ( "AnchorType",
1357                                           TextContentAnchorType.AT_PARAGRAPH );
1358             xEllipseProps.setPropertyValue ( "AnchorType",
1359                                              TextContentAnchorType.AT_PARAGRAPH );
1360 
1361             // Access the XDrawPageSupplier interface of the document
1362             XDrawPageSupplier xDrawPageSupplier = (XDrawPageSupplier)
1363                 UnoRuntime.queryInterface (XDrawPageSupplier.class, mxDoc );
1364 
1365             // Get the XShapes interface of the draw page
1366             XShapes xShapes = ( XShapes ) UnoRuntime.queryInterface (
1367                 XShapes.class, xDrawPageSupplier.getDrawPage () );
1368 
1369             // Add both shapes
1370             xShapes.add ( xEllipse );
1371             xShapes.add ( xRect );
1372 
1373             /*
1374               This doesn't work, I am assured that FME and AMA are fixing it.
1375 
1376               XShapes xGrouper = (XShapes) UnoRuntime.queryInterface(
1377               XShapes.class, mxDocFactory.createInstance (
1378               "com.sun.star.drawing.GroupShape" ) );
1379 
1380               XShape xGrouperShape = (XShape) UnoRuntime.queryInterface(
1381                      XShape.class, xGrouper );
1382               xShapes.add ( xGrouperShape );
1383 
1384               xGrouper.add ( xRect );
1385               xGrouper.add ( xEllipse );
1386 
1387               XShapeGrouper xShapeGrouper = (XShapeGrouper)
1388               UnoRuntime.queryInterface(XShapeGrouper.class, xShapes);
1389               xShapeGrouper.group ( xGrouper );
1390             */
1391 
1392         }
1393         catch (Exception e)
1394         {
1395             e.printStackTrace();
1396         }
1397     }
1398 
1399     /** This method demonstrates how to create, insert and apply styles
1400      */
StylesExample()1401     protected void StylesExample ()
1402     {
1403         try
1404         {
1405             // Go to the end of the document
1406             mxDocCursor.gotoEnd( false );
1407 
1408             // Insert two paragraph breaks
1409             mxDocText.insertControlCharacter (
1410                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1411             mxDocText.insertControlCharacter (
1412                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1413 
1414             // Create a new style from the document's factory
1415             XStyle xStyle = (XStyle) UnoRuntime.queryInterface(
1416                 XStyle.class, mxDocFactory.createInstance(
1417                     "com.sun.star.style.ParagraphStyle" ) );
1418 
1419             // Access the XPropertySet interface of the new style
1420             XPropertySet xStyleProps = (XPropertySet) UnoRuntime.queryInterface(
1421                 XPropertySet.class, xStyle );
1422 
1423             // Give the new style a light blue background
1424             xStyleProps.setPropertyValue ( "ParaBackColor", new Integer (13421823));
1425 
1426             // Get the StyleFamiliesSupplier interface of the document
1427             XStyleFamiliesSupplier xSupplier = (XStyleFamiliesSupplier)
1428                 UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, mxDoc);
1429 
1430             // Use the StyleFamiliesSupplier interface to get the XNameAccess
1431             // interface of the actual style families
1432             XNameAccess xFamilies = ( XNameAccess ) UnoRuntime.queryInterface (
1433                 XNameAccess.class, xSupplier.getStyleFamilies() );
1434 
1435             // Access the 'ParagraphStyles' Family
1436             XNameContainer xFamily = (XNameContainer ) UnoRuntime.queryInterface (
1437                         XNameContainer.class,
1438                         xFamilies.getByName ( "ParagraphStyles" ) );
1439 
1440             // Insert the newly created style into the ParagraphStyles family
1441             xFamily.insertByName ( "All-Singing All-Dancing Style", xStyle );
1442 
1443             // Get the XParagraphCursor interface of the document cursor
1444             XParagraphCursor xParaCursor = (XParagraphCursor)
1445                 UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1446 
1447             // Select the first paragraph inserted
1448             xParaCursor.gotoPreviousParagraph ( false );
1449             xParaCursor.gotoPreviousParagraph ( true );
1450 
1451             // Access the property set of the cursor selection
1452             XPropertySet xCursorProps = (XPropertySet) UnoRuntime.queryInterface(
1453                 XPropertySet.class, mxDocCursor );
1454 
1455             // Set the style of the cursor selection to our newly created style
1456             xCursorProps.setPropertyValue ( "ParaStyleName",
1457                                             "All-Singing All-Dancing Style" );
1458 
1459             // Go back to the end
1460             mxDocCursor.gotoEnd ( false );
1461 
1462             // Select the last paragraph in the document
1463             xParaCursor.gotoNextParagraph ( true );
1464 
1465             // And reset its style to 'Standard' (the programmatic name for
1466             // the default style)
1467             xCursorProps.setPropertyValue ( "ParaStyleName", "Standard" );
1468         }
1469         catch (Exception e)
1470         {
1471             e.printStackTrace();
1472         }
1473     }
1474 
1475     /** This method demonstrates how to set numbering types and numbering levels
1476         using the com.sun.star.text.NumberingRules service
1477      */
NumberingExample()1478     protected void NumberingExample ()
1479     {
1480         try
1481         {
1482             // Go to the end of the document
1483             mxDocCursor.gotoEnd( false );
1484             // Get the RelativeTextContentInsert interface of the document
1485             XRelativeTextContentInsert xRelative =
1486                 (XRelativeTextContentInsert ) UnoRuntime.queryInterface (
1487                     XRelativeTextContentInsert.class, mxDocText );
1488 
1489             // Use the document's factory to create the NumberingRules service,
1490             // and get its XIndexAccess interface
1491             XIndexAccess xNum = (XIndexAccess) UnoRuntime.queryInterface(
1492                 XIndexAccess.class,
1493                 mxDocFactory.createInstance( "com.sun.star.text.NumberingRules" ) );
1494 
1495             // Also get the NumberingRule's XIndexReplace interface
1496             XIndexReplace xReplace = (XIndexReplace) UnoRuntime.queryInterface(
1497                 XIndexReplace.class, xNum );
1498 
1499             // Create an array of XPropertySets, one for each of the three
1500             // paragraphs we're about to create
1501             XPropertySet xParas[] = new XPropertySet [ 3 ];
1502             for ( int i = 0 ; i < 3 ; ++ i )
1503             {
1504                 // Create a new paragraph
1505                 XTextContent xNewPara = (XTextContent) UnoRuntime.queryInterface(
1506                     XTextContent.class, mxDocFactory.createInstance(
1507                         "com.sun.star.text.Paragraph" ) );
1508 
1509                 // Get the XPropertySet interface of the new paragraph and put
1510                 // it in our array
1511                 xParas[i] = (XPropertySet) UnoRuntime.queryInterface(
1512                     XPropertySet.class, xNewPara );
1513 
1514                 // Insert the new paragraph into the document after the fish
1515                 // section. As it is an insert relative to the fish section, the
1516                 // first paragraph inserted will be below the next two
1517                 xRelative.insertTextContentAfter ( xNewPara, mxFishSection );
1518 
1519                 // Separate from the above, but also needs to be done three times
1520 
1521                 // Get the PropertyValue sequence for this numbering level
1522                 PropertyValue [] aProps = (PropertyValue [] ) xNum.getByIndex ( i );
1523 
1524                 // Iterate over the PropertyValue's for this numbering level,
1525                 // looking for the 'NumberingType' property
1526                 for ( int j = 0 ; j < aProps.length ; ++j )
1527                 {
1528                     if ( aProps[j].Name.equals ( "NumberingType" ) )
1529                     {
1530                         // Once we find it, set its value to a new type,
1531                         // dependent on which numbering level we're currently on
1532                         switch ( i )
1533                         {
1534                         case 0 : aProps[j].Value =
1535                                      new Short(NumberingType.ROMAN_UPPER);
1536                             break;
1537                         case 1 : aProps[j].Value =
1538                                      new Short(NumberingType.CHARS_UPPER_LETTER);
1539                             break;
1540                         case 2 : aProps[j].Value =
1541                                      new Short(NumberingType.ARABIC);
1542                             break;
1543                         }
1544                         // Put the updated PropertyValue sequence back into the
1545                         // NumberingRules service
1546                         xReplace.replaceByIndex ( i, aProps );
1547                         break;
1548                     }
1549                 }
1550             }
1551             // Get the XParagraphCursor interface of our text cursor
1552             XParagraphCursor xParaCursor = (XParagraphCursor)
1553                 UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1554             // Go to the end of the document, then select the preceding paragraphs
1555             mxDocCursor.gotoEnd ( false );
1556             xParaCursor.gotoPreviousParagraph ( false );
1557             xParaCursor.gotoPreviousParagraph ( true );
1558             xParaCursor.gotoPreviousParagraph ( true );
1559 
1560             // Get the XPropertySet of the cursor's currently selected text
1561             XPropertySet xCursorProps = (XPropertySet) UnoRuntime.queryInterface(
1562                 XPropertySet.class, mxDocCursor );
1563 
1564             // Set the updated Numbering rules to the cursor's property set
1565             xCursorProps.setPropertyValue ( "NumberingRules", xNum );
1566             mxDocCursor.gotoEnd( false );
1567 
1568             // Set the first paragraph that was inserted to a numbering level of
1569             // 2 (thus it will have Arabic style numbering)
1570             xParas[0].setPropertyValue ( "NumberingLevel", new Short((short) 2));
1571 
1572             // Set the second paragraph that was inserted to a numbering level of
1573             // 1 (thus it will have 'Chars Upper Letter' style numbering)
1574             xParas[1].setPropertyValue ( "NumberingLevel", new Short((short) 1));
1575 
1576             // Set the third paragraph that was inserted to a numbering level of
1577             // 0 (thus it will have 'Chars Upper Letter' style numbering)
1578             xParas[2].setPropertyValue ( "NumberingLevel", new Short((short) 0));
1579             }
1580         catch (Exception e)
1581         {
1582             e.printStackTrace();
1583         }
1584     }
1585 
1586     /** This method demonstrates how to create linked and unlinked sections
1587      */
TextSectionExample()1588     protected void TextSectionExample ()
1589     {
1590         try
1591         {
1592             // Go to the end of the document
1593             mxDocCursor.gotoEnd( false );
1594             // Insert two paragraph breaks
1595             mxDocText.insertControlCharacter (
1596                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1597             mxDocText.insertControlCharacter (
1598                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, true );
1599 
1600             // Create a new TextSection from the document factory and access
1601             // its XNamed interface
1602             XNamed xChildNamed = (XNamed) UnoRuntime.queryInterface(
1603                 XNamed.class, mxDocFactory.createInstance(
1604                     "com.sun.star.text.TextSection" ) );
1605             // Set the new sections name to 'Child_Section'
1606             xChildNamed.setName ( "Child_Section" );
1607 
1608             // Access the Child_Section's XTextContent interface and insert it
1609             // into the document
1610             XTextContent xChildSection = (XTextContent) UnoRuntime.queryInterface(
1611                 XTextContent.class, xChildNamed );
1612             mxDocText.insertTextContent ( mxDocCursor, xChildSection, false );
1613 
1614             // Access the XParagraphCursor interface of our text cursor
1615             XParagraphCursor xParaCursor = (XParagraphCursor)
1616                 UnoRuntime.queryInterface(XParagraphCursor.class, mxDocCursor);
1617 
1618             // Go back one paragraph (into Child_Section)
1619             xParaCursor.gotoPreviousParagraph ( false );
1620 
1621             // Insert a string into the Child_Section
1622             mxDocText.insertString ( mxDocCursor, "This is a test", false );
1623 
1624             // Go to the end of the document
1625             mxDocCursor.gotoEnd( false );
1626 
1627             // Go back two paragraphs
1628             xParaCursor.gotoPreviousParagraph ( false );
1629             xParaCursor.gotoPreviousParagraph ( false );
1630             // Go to the end of the document, selecting the two paragraphs
1631             mxDocCursor.gotoEnd ( true );
1632 
1633             // Create another text section and access its XNamed interface
1634             XNamed xParentNamed = (XNamed) UnoRuntime.queryInterface(XNamed.class,
1635                       mxDocFactory.createInstance("com.sun.star.text.TextSection"));
1636 
1637             // Set this text section's name to Parent_Section
1638             xParentNamed.setName ( "Parent_Section" );
1639 
1640             // Access the Parent_Section's XTextContent interface ...
1641             XTextContent xParentSection = (XTextContent) UnoRuntime.queryInterface(
1642                 XTextContent.class, xParentNamed );
1643             // ...and insert it into the document
1644             mxDocText.insertTextContent ( mxDocCursor, xParentSection, false );
1645 
1646             // Go to the end of the document
1647             mxDocCursor.gotoEnd ( false );
1648             // Insert a new paragraph
1649             mxDocText.insertControlCharacter (
1650                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1651             // And select the new paragraph
1652             xParaCursor.gotoPreviousParagraph ( true );
1653 
1654             // Create a new Text Section and access its XNamed interface
1655             XNamed xLinkNamed = (XNamed) UnoRuntime.queryInterface(XNamed.class,
1656                       mxDocFactory.createInstance("com.sun.star.text.TextSection"));
1657             // Set the new text section's name to Linked_Section
1658             xLinkNamed.setName ( "Linked_Section" );
1659 
1660             // Access the Linked_Section's XTextContent interface
1661             XTextContent xLinkedSection = (XTextContent) UnoRuntime.queryInterface(
1662                 XTextContent.class, xLinkNamed );
1663             // And insert the Linked_Section into the document
1664             mxDocText.insertTextContent ( mxDocCursor, xLinkedSection, false );
1665 
1666             // Access the Linked_Section's XPropertySet interface
1667             XPropertySet xLinkProps = (XPropertySet)UnoRuntime.queryInterface(
1668                 XPropertySet.class, xLinkNamed );
1669             // Set the linked section to be linked to the Child_Section
1670             xLinkProps.setPropertyValue ( "LinkRegion", "Child_Section" );
1671 
1672             // Access the XPropertySet interface of the Child_Section
1673             XPropertySet xChildProps = (XPropertySet) UnoRuntime.queryInterface(
1674                 XPropertySet.class, xChildNamed );
1675             // Set the Child_Section's background color to blue
1676             xChildProps.setPropertyValue( "BackColor", new Integer(13421823));
1677 
1678             // Refresh the document, so the linked section matches the Child_Section
1679             XRefreshable xRefresh = (XRefreshable) UnoRuntime.queryInterface(
1680                 XRefreshable.class, mxDoc );
1681             xRefresh.refresh();
1682         }
1683         catch (Exception e)
1684         {
1685             e.printStackTrace();
1686         }
1687     }
1688 
1689     /** This method demonstrates the XTextColumns interface and how to insert a
1690         blank paragraph using the XRelativeTextContentInsert interface
1691      */
TextColumnsExample()1692     protected void TextColumnsExample ()
1693     {
1694         try
1695         {
1696             // Go to the end of the document
1697             mxDocCursor.gotoEnd( false );
1698             // insert a new paragraph
1699             mxDocText.insertControlCharacter (
1700                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1701 
1702             // insert the string 'I am a fish.' 100 times
1703             for ( int i = 0 ; i < 100 ; ++i )
1704             {
1705                 mxDocText.insertString ( mxDocCursor, "I am a fish.", false );
1706             }
1707             // insert a paragraph break after the text
1708             mxDocText.insertControlCharacter (
1709                 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1710 
1711             // Get the XParagraphCursor interface of our text cursor
1712             XParagraphCursor xParaCursor = (XParagraphCursor)
1713                 UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1714             // Jump back before all the text we just inserted
1715             xParaCursor.gotoPreviousParagraph ( false );
1716             xParaCursor.gotoPreviousParagraph ( false );
1717 
1718             // Insert a string at the beginning of the block of text
1719             mxDocText.insertString ( mxDocCursor, "Fish section begins:", false );
1720 
1721             // Then select all of the text
1722             xParaCursor.gotoNextParagraph ( true );
1723             xParaCursor.gotoNextParagraph ( true );
1724 
1725             // Create a new text section and get its XNamed interface
1726             XNamed xSectionNamed = (XNamed) UnoRuntime.queryInterface(XNamed.class,
1727                       mxDocFactory.createInstance("com.sun.star.text.TextSection"));
1728 
1729             // Set the name of our new section (appropriately) to 'Fish'
1730             xSectionNamed.setName ( "Fish" );
1731 
1732             // Create the TextColumns service and get its XTextColumns interface
1733             XTextColumns xColumns = (XTextColumns) UnoRuntime.queryInterface(
1734                 XTextColumns.class,
1735                 mxDocFactory.createInstance ( "com.sun.star.text.TextColumns" ) );
1736 
1737             // We want three columns
1738             xColumns.setColumnCount ( (short) 3 );
1739 
1740             // Get the TextColumns, and make the middle one narrow with a larger
1741             // margin on the left than the right
1742             TextColumn[] aSequence = xColumns.getColumns ();
1743             aSequence[1].Width /= 2;
1744             aSequence[1].LeftMargin = 350;
1745             aSequence[1].RightMargin = 200;
1746             // Set the updated TextColumns back to the XTextColumns
1747             xColumns.setColumns ( aSequence );
1748 
1749             // Get the property set interface of our 'Fish' section
1750             XPropertySet xSectionProps = (XPropertySet) UnoRuntime.queryInterface(
1751                 XPropertySet.class, xSectionNamed );
1752 
1753             // Set the columns to the Text Section
1754             xSectionProps.setPropertyValue ( "TextColumns", xColumns );
1755 
1756             // Get the XTextContent interface of our 'Fish' section
1757             mxFishSection = (XTextContent) UnoRuntime.queryInterface(
1758                 XTextContent.class, xSectionNamed );
1759 
1760             // Insert the 'Fish' section over the currently selected text
1761             mxDocText.insertTextContent ( mxDocCursor, mxFishSection, true );
1762 
1763             // Get the wonderful XRelativeTextContentInsert interface
1764             XRelativeTextContentInsert xRelative = (XRelativeTextContentInsert )
1765                 UnoRuntime.queryInterface (
1766                     XRelativeTextContentInsert.class, mxDocText );
1767 
1768             // Create a new empty paragraph and get its XTextContent interface
1769             XTextContent xNewPara = (XTextContent) UnoRuntime.queryInterface(
1770                 XTextContent.class,
1771                 mxDocFactory.createInstance("com.sun.star.text.Paragraph"));
1772 
1773             // Insert the empty paragraph after the fish Text Section
1774             xRelative.insertTextContentAfter ( xNewPara, mxFishSection );
1775         }
1776         catch (Exception e)
1777         {
1778             e.printStackTrace();
1779         }
1780     }
1781 }
1782