1 /*************************************************************************
3 * $RCSfile: TextDocuments.java,v $
7 * last change: $Author: rt $ $Date: 2005-01-31 16:56:34 $
9 * The Contents of this file are made available subject to the terms of
12 * Copyright (c) 2003 by Sun Microsystems, Inc.
13 * All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. Neither the name of Sun Microsystems, Inc. nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
30 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
31 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *************************************************************************/
41 import com
.sun
.star
.awt
.Point
;
42 import com
.sun
.star
.awt
.Size
;
43 import com
.sun
.star
.awt
.FontWeight
;
45 import com
.sun
.star
.beans
.PropertyState
;
46 import com
.sun
.star
.beans
.PropertyValue
;
47 import com
.sun
.star
.beans
.XPropertySet
;
48 import com
.sun
.star
.beans
.XPropertyState
;
50 import com
.sun
.star
.bridge
.XUnoUrlResolver
;
52 import com
.sun
.star
.comp
.servicemanager
.ServiceManager
;
54 import com
.sun
.star
.connection
.XConnector
;
55 import com
.sun
.star
.connection
.XConnection
;
57 import com
.sun
.star
.container
.XNameAccess
;
58 import com
.sun
.star
.container
.XNameContainer
;
59 import com
.sun
.star
.container
.XNamed
;
60 import com
.sun
.star
.container
.XIndexAccess
;
61 import com
.sun
.star
.container
.XIndexReplace
;
62 import com
.sun
.star
.container
.XEnumeration
;
63 import com
.sun
.star
.container
.XEnumerationAccess
;
65 import com
.sun
.star
.drawing
.XShape
;
66 import com
.sun
.star
.drawing
.XShapeGrouper
;
67 import com
.sun
.star
.drawing
.XShapes
;
68 import com
.sun
.star
.drawing
.XDrawPageSupplier
;
70 import com
.sun
.star
.frame
.XDesktop
;
71 import com
.sun
.star
.frame
.XComponentLoader
;
72 import com
.sun
.star
.frame
.XModel
;
73 import com
.sun
.star
.frame
.XController
;
75 import com
.sun
.star
.lang
.XComponent
;
76 import com
.sun
.star
.lang
.XMultiComponentFactory
;
77 import com
.sun
.star
.lang
.XMultiServiceFactory
;
78 import com
.sun
.star
.lang
.XServiceInfo
;
80 import com
.sun
.star
.style
.NumberingType
;
81 import com
.sun
.star
.style
.XStyle
;
82 import com
.sun
.star
.style
.XStyleFamiliesSupplier
;
84 import com
.sun
.star
.table
.XCell
;
86 import com
.sun
.star
.text
.ControlCharacter
;
87 import com
.sun
.star
.text
.ReferenceFieldSource
;
88 import com
.sun
.star
.text
.ReferenceFieldPart
;
89 import com
.sun
.star
.text
.TextColumn
;
90 import com
.sun
.star
.text
.TextContentAnchorType
;
91 import com
.sun
.star
.text
.XAutoTextContainer
;
92 import com
.sun
.star
.text
.XAutoTextGroup
;
93 import com
.sun
.star
.text
.XAutoTextEntry
;
94 import com
.sun
.star
.text
.XDependentTextField
;
95 import com
.sun
.star
.text
.XDocumentIndex
;
96 import com
.sun
.star
.text
.XFootnote
;
97 import com
.sun
.star
.text
.XFootnotesSupplier
;
98 import com
.sun
.star
.text
.XParagraphCursor
;
99 import com
.sun
.star
.text
.XReferenceMarksSupplier
;
100 import com
.sun
.star
.text
.XRelativeTextContentInsert
;
101 import com
.sun
.star
.text
.XSentenceCursor
;
102 import com
.sun
.star
.text
.XSimpleText
;
103 import com
.sun
.star
.text
.XText
;
104 import com
.sun
.star
.text
.XTextColumns
;
105 import com
.sun
.star
.text
.XTextContent
;
106 import com
.sun
.star
.text
.XTextCursor
;
107 import com
.sun
.star
.text
.XTextDocument
;
108 import com
.sun
.star
.text
.XTextField
;
109 import com
.sun
.star
.text
.XTextFrame
;
110 import com
.sun
.star
.text
.XTextRange
;
111 import com
.sun
.star
.text
.XTextSection
;
112 import com
.sun
.star
.text
.XTextTable
;
113 import com
.sun
.star
.text
.XTextTableCursor
;
114 import com
.sun
.star
.text
.XTextTablesSupplier
;
115 import com
.sun
.star
.text
.XTextFieldsSupplier
;
116 import com
.sun
.star
.text
.XBookmarksSupplier
;
117 import com
.sun
.star
.text
.XTextViewCursorSupplier
;
118 import com
.sun
.star
.text
.XTextViewCursor
;
119 import com
.sun
.star
.text
.XPageCursor
;
121 import com
.sun
.star
.text
.XWordCursor
;
123 import com
.sun
.star
.uno
.AnyConverter
;
124 import com
.sun
.star
.uno
.UnoRuntime
;
125 import com
.sun
.star
.uno
.XComponentContext
;
126 import com
.sun
.star
.uno
.XInterface
;
127 import com
.sun
.star
.uno
.XNamingService
;
129 import com
.sun
.star
.util
.XRefreshable
;
131 import com
.sun
.star
.frame
.XStorable
;
132 import com
.sun
.star
.view
.XPrintable
;
134 import java
.lang
.Math
;
135 import java
.util
.Random
;
136 import java
.util
.Hashtable
;
141 * Created on 11. April 2002, 08:47
146 * @author Martin Gallwey, Dietrich Schulten
148 public class TextDocuments
{
149 // adjust these constant to your local printer!
150 private static String sOutputDir
;
152 private String aPrinterName
= "\\\\so-print\\xml3sof";
154 private XComponentContext mxRemoteContext
= null;
155 private XMultiComponentFactory mxRemoteServiceManager
= null;
156 private XTextDocument mxDoc
= null;
157 private XMultiServiceFactory mxDocFactory
= null;
158 private XMultiServiceFactory mxFactory
= null;
159 private XPropertySet mxDocProps
= null;
160 private XText mxDocText
= null;
161 private XTextCursor mxDocCursor
= null;
162 private XTextContent mxFishSection
= null;
163 private Random maRandom
= null;
165 /** Creates a new instance of TextDocuments */
166 public TextDocuments() {
170 * @param args the command line arguments
172 public static void main(String
[] args
) {
173 TextDocuments textDocuments1
= new TextDocuments();
175 // output directory for store test;
176 sOutputDir
= args
[0];
178 textDocuments1
.runDemo();
180 catch (java
.lang
.Exception e
){
181 System
.out
.println(e
.getMessage());
189 protected void runDemo() throws java
.lang
.Exception
{
190 storePrintExample(); // depends on printer name
192 viewCursorExample(); // makes changes to the current document,
197 /** Sample for use of templates
198 * This sample uses the file TextTemplateWithUserFields.odt from the Samples
199 * folder. The file contains a number of User text fields (Variables - User)
200 * and a bookmark which we use to fill in various values
202 protected void templateExample() throws java
.lang
.Exception
{
203 // create a small hashtable that simulates a rowset
204 Hashtable recipient
= new Hashtable();
205 recipient
.put("Company", "Manatee Books");
206 recipient
.put("Contact", "Rod Martin");
207 recipient
.put("ZIP", "34567");
208 recipient
.put("City", "Fort Lauderdale");
209 recipient
.put("State", "Florida");
211 // load template with User fields and bookmark
212 java
.io
.File sourceFile
= new java
.io
.File("TextTemplateWithUserFields.odt");
213 StringBuffer sTemplateFileUrl
= new StringBuffer("file:///");
214 sTemplateFileUrl
.append(sourceFile
.getCanonicalPath().replace('\\', '/'));
216 XComponent xTemplateComponent
=
217 newDocComponentFromTemplate( sTemplateFileUrl
.toString() );
219 // get XTextFieldsSupplier, XBookmarksSupplier interfaces
220 XTextFieldsSupplier xTextFieldsSupplier
= (XTextFieldsSupplier
)
221 UnoRuntime
.queryInterface(XTextFieldsSupplier
.class,
223 XBookmarksSupplier xBookmarksSupplier
= (XBookmarksSupplier
)
224 UnoRuntime
.queryInterface(XBookmarksSupplier
.class, xTemplateComponent
);
226 // access the TextFields and the TextFieldMasters collections
227 XNameAccess xNamedFieldMasters
= xTextFieldsSupplier
.getTextFieldMasters();
228 XEnumerationAccess xEnumeratedFields
= xTextFieldsSupplier
.getTextFields();
230 // iterate over hashtable and insert values into field masters
231 java
.util
.Enumeration keys
= recipient
.keys();
232 while(keys
.hasMoreElements()) {
234 String key
= (String
)keys
.nextElement();
236 // access corresponding field master
237 Object fieldMaster
= xNamedFieldMasters
.getByName(
238 "com.sun.star.text.fieldmaster.User." + key
);
240 // query the XPropertySet interface, we need to set the Content property
241 XPropertySet xPropertySet
= (XPropertySet
)UnoRuntime
.queryInterface(
242 XPropertySet
.class, fieldMaster
);
244 // insert the column value into field master
245 xPropertySet
.setPropertyValue("Content", recipient
.get(key
));
247 // afterwards we must refresh the textfields collection
248 XRefreshable xRefreshable
= (XRefreshable
)UnoRuntime
.queryInterface(
249 XRefreshable
.class, xEnumeratedFields
);
250 xRefreshable
.refresh();
252 // accessing the Bookmarks collection of the document
253 XNameAccess xNamedBookmarks
= xBookmarksSupplier
.getBookmarks();
255 // find the bookmark named "Subscription"
256 Object bookmark
= xNamedBookmarks
.getByName("Subscription");
257 // we need its XTextRange which is available from getAnchor(),
258 // so query for XTextContent
259 XTextContent xBookmarkContent
= (XTextContent
)UnoRuntime
.queryInterface(
260 XTextContent
.class, bookmark
);
261 // get the anchor of the bookmark (its XTextRange)
262 XTextRange xBookmarkRange
= xBookmarkContent
.getAnchor();
263 // set string at the bookmark position
264 xBookmarkRange
.setString("subscription for the Manatee Journal");
268 /** Sample for document changes, starting at the current view cursor position
269 * The sample changes the paragraph style and the character style at the
270 * current view cursor selection Open the sample file ViewCursorExampleFile,
271 * select some text and run the example.
272 * The current paragraph will be set to Quotations paragraph style.
273 * The selected text will be set to Quotation character style.
275 private void viewCursorExample() throws java
.lang
.Exception
{
276 // get the remote service manager
277 mxRemoteServiceManager
= this.getRemoteServiceManager();
278 // get the Desktop service
279 Object desktop
= mxRemoteServiceManager
.createInstanceWithContext(
280 "com.sun.star.frame.Desktop", mxRemoteContext
);
281 // query its XDesktop interface, we need the current component
282 XDesktop xDesktop
= (XDesktop
)UnoRuntime
.queryInterface(
283 XDesktop
.class, desktop
);
284 // retrieve the current component and access the controller
285 XComponent xCurrentComponent
= xDesktop
.getCurrentComponent();
286 XModel xModel
= (XModel
)UnoRuntime
.queryInterface(XModel
.class,
288 XController xController
= xModel
.getCurrentController();
289 // the controller gives us the TextViewCursor
290 XTextViewCursorSupplier xViewCursorSupplier
=
291 (XTextViewCursorSupplier
)UnoRuntime
.queryInterface(
292 XTextViewCursorSupplier
.class, xController
);
293 XTextViewCursor xViewCursor
= xViewCursorSupplier
.getViewCursor();
295 // query its XPropertySet interface, we want to set character and paragraph
297 XPropertySet xCursorPropertySet
= (XPropertySet
)UnoRuntime
.queryInterface(
298 XPropertySet
.class, xViewCursor
);
299 // set the appropriate properties for character and paragraph style
300 xCursorPropertySet
.setPropertyValue("CharStyleName", "Quotation");
301 xCursorPropertySet
.setPropertyValue("ParaStyleName", "Quotations");
302 // print the current page number
303 XPageCursor xPageCursor
= (XPageCursor
)UnoRuntime
.queryInterface(
304 XPageCursor
.class, xViewCursor
);
305 System
.out
.println("The current page number is " + xPageCursor
.getPage());
306 // the model cursor is much more powerful, so
307 // we create a model cursor at the current view cursor position with the
309 // get the Text service from the TextViewCursor, it is an XTextRange:
310 XText xDocumentText
= xViewCursor
.getText();
311 // create a model cursor from the viewcursor
312 XTextCursor xModelCursor
= xDocumentText
.createTextCursorByRange(
313 xViewCursor
.getStart());
314 // now we could query XWordCursor, XSentenceCursor and XParagraphCursor
315 // or XDocumentInsertable, XSortable or XContentEnumerationAccess
316 // and work with the properties of com.sun.star.text.TextCursor
317 // in this case we just go to the end of the paragraph and add some text.
318 XParagraphCursor xParagraphCursor
= (XParagraphCursor
)
319 UnoRuntime
.queryInterface(XParagraphCursor
.class, xModelCursor
);
320 // goto the end of the paragraph
321 xParagraphCursor
.gotoEndOfParagraph(false);
322 xParagraphCursor
.setString(" ***** Fin de semana! ******");
326 /** Sample for the various editing facilities described in the
329 private void editingExample () throws java
.lang
.Exception
{
330 // create empty swriter document
331 XComponent xEmptyWriterComponent
= newDocComponent("swriter");
332 // query its XTextDocument interface to get the text
333 mxDoc
= (XTextDocument
)UnoRuntime
.queryInterface(
334 XTextDocument
.class, xEmptyWriterComponent
);
336 // get a reference to the body text of the document
337 mxDocText
= mxDoc
.getText();
339 // Get a reference to the document's property set. This contains document
340 // information like the current word count
341 mxDocProps
= (XPropertySet
) UnoRuntime
.queryInterface(
342 XPropertySet
.class, mxDoc
);
344 // Simple text insertion example
346 // Example using text ranges to insert strings at the beginning or end
349 // Create a document cursor and remember it, it will be used in most
350 // of the following examples
351 mxDocCursor
= mxDocText
.createTextCursor();
352 // Demonstrate some of the different cursor types (word, sentence)
353 TextCursorExample ();
355 // Access the text document's multi service factory, which we will need
356 // for most of the following examples
357 mxDocFactory
= (XMultiServiceFactory
) UnoRuntime
.queryInterface(
358 XMultiServiceFactory
.class, mxDoc
);
360 // Examples of text fields, dependant text fields and field masters
363 // Example of using an XEnumerationAccess to iterate over paragraphs and
364 // set properties of each paragraph as we do so
367 // Example of creating and manipulating a text frame
370 // Example of creating and manipulating a text table, text table rows
371 // and text table cells get a new random generator
372 maRandom
= new Random();
375 // Example of creating, inserting and manipulating text sections, as
376 // well as an example of how to refresh the document
377 TextSectionExample ();
379 // Example of creating a text section over a block of text and formatting
380 // the text section into columns, as well as how to insert an empty
381 // paragraph using the XRelativeTextContentInsert
382 TextColumnsExample ();
384 // Example of creating the NumberingRules service and adjusting
385 // NumberingTypes and NumberingLevels
388 // Example of how to use the XStyleFamiliesSupplier interface of the
389 // document and how to create, insert and apply styles
393 // Example of how to create and manipulate reference marks and GetReference
397 // Example of how to create and insert Footnotes and how to use the
398 // XFootnotesSupplier interface of the document
401 // This method demonstrates how to create shapes from the document factory
402 // and how to access the draw page of the document using the
403 // XDrawPageSupplier interface
406 mxFactory
= (XMultiServiceFactory
)UnoRuntime
.queryInterface(
407 XMultiServiceFactory
.class, mxRemoteServiceManager
);
408 // This example demonstrates the use of the AutoTextContainer,
409 // AutoTextGroup and AutoTextEntry services and shows how to create,
410 // insert and modify auto text blocks
414 protected void storePrintExample() throws java
.lang
.Exception
{
415 // get the remote service manager
416 mxRemoteServiceManager
= this.getRemoteServiceManager();
417 // retrieve the Desktop object, we need its XComponentLoader
418 Object desktop
= mxRemoteServiceManager
.createInstanceWithContext(
419 "com.sun.star.frame.Desktop", mxRemoteContext
);
420 XComponentLoader xComponentLoader
= (XComponentLoader
)
421 UnoRuntime
.queryInterface(XComponentLoader
.class, desktop
);
422 PropertyValue
[] loadProps
= new PropertyValue
[0];
424 java
.io
.File sourceFile
= new java
.io
.File("PrintDemo.odt");
425 StringBuffer sLoadFileUrl
= new StringBuffer("file:///");
426 sLoadFileUrl
.append(sourceFile
.getCanonicalPath().replace('\\', '/'));
428 XComponent xDoc
= xComponentLoader
.loadComponentFromURL(
429 sLoadFileUrl
.toString(), "_blank", 0, loadProps
);
431 if ( xDoc
!= null ) {
432 sourceFile
= new java
.io
.File(sOutputDir
);
433 StringBuffer sStoreFileUrl
= new StringBuffer();
434 sStoreFileUrl
.append(sourceFile
.toURL().toString());
435 sStoreFileUrl
.append("somepopularfileformat.doc");
437 storeDocComponent(xDoc
, sStoreFileUrl
.toString() );
438 printDocComponent(xDoc
);
442 private XMultiComponentFactory
getRemoteServiceManager()
443 throws java
.lang
.Exception
445 if (mxRemoteContext
== null && mxRemoteServiceManager
== null) {
446 // get the remote office context. If necessary a new office
447 // process is started
448 mxRemoteContext
= com
.sun
.star
.comp
.helper
.Bootstrap
.bootstrap();
449 System
.out
.println("Connected to a running office ...");
450 mxRemoteServiceManager
= mxRemoteContext
.getServiceManager();
452 return mxRemoteServiceManager
;
455 protected XComponent
newDocComponent(String docType
)
456 throws java
.lang
.Exception
458 String loadUrl
= "private:factory/" + docType
;
459 mxRemoteServiceManager
= this.getRemoteServiceManager();
460 Object desktop
= mxRemoteServiceManager
.createInstanceWithContext(
461 "com.sun.star.frame.Desktop", mxRemoteContext
);
462 XComponentLoader xComponentLoader
= (XComponentLoader
)
463 UnoRuntime
.queryInterface(XComponentLoader
.class, desktop
);
464 PropertyValue
[] loadProps
= new PropertyValue
[0];
465 return xComponentLoader
.loadComponentFromURL(loadUrl
, "_blank",
469 /** Load a document as template
471 protected XComponent
newDocComponentFromTemplate(String loadUrl
)
472 throws java
.lang
.Exception
474 // get the remote service manager
475 mxRemoteServiceManager
= this.getRemoteServiceManager();
476 // retrieve the Desktop object, we need its XComponentLoader
477 Object desktop
= mxRemoteServiceManager
.createInstanceWithContext(
478 "com.sun.star.frame.Desktop", mxRemoteContext
);
479 XComponentLoader xComponentLoader
= (XComponentLoader
)
480 UnoRuntime
.queryInterface(XComponentLoader
.class, desktop
);
482 // define load properties according to com.sun.star.document.MediaDescriptor
483 // the boolean property AsTemplate tells the office to create a new document
484 // from the given file
485 PropertyValue
[] loadProps
= new PropertyValue
[1];
486 loadProps
[0] = new PropertyValue();
487 loadProps
[0].Name
= "AsTemplate";
488 loadProps
[0].Value
= new Boolean(true);
490 return xComponentLoader
.loadComponentFromURL(loadUrl
, "_blank",
494 /** Load a document with arguments (text purposes)
496 protected void storeDocComponent(XComponent xDoc
, String storeUrl
)
497 throws java
.lang
.Exception
500 XStorable xStorable
= (XStorable
)UnoRuntime
.queryInterface(
501 XStorable
.class, xDoc
);
502 PropertyValue
[] storeProps
= new PropertyValue
[1];
503 storeProps
[0] = new PropertyValue();
504 storeProps
[0].Name
= "FilterName";
505 storeProps
[0].Value
= "MS Word 97";
507 System
.out
.println("... store \"PrintDemo.odt\" to \"" + storeUrl
+ "\".");
508 xStorable
.storeAsURL(storeUrl
, storeProps
);
511 protected void printDocComponent(XComponent xDoc
) throws java
.lang
.Exception
{
512 XPrintable xPrintable
= (XPrintable
)UnoRuntime
.queryInterface(
513 XPrintable
.class, xDoc
);
514 PropertyValue
[] printerDesc
= new PropertyValue
[1];
515 printerDesc
[0] = new PropertyValue();
516 printerDesc
[0].Name
= "Name";
517 printerDesc
[0].Value
= aPrinterName
;
519 xPrintable
.setPrinter(printerDesc
);
521 PropertyValue
[] printOpts
= new PropertyValue
[1];
522 printOpts
[0] = new PropertyValue();
523 printOpts
[0].Name
= "Pages";
524 printOpts
[0].Value
= "1";
526 xPrintable
.print(printOpts
);
529 // Setting the whole text of a document as one string
530 protected void BodyTextExample ()
532 // Body Text and TextDocument example
535 // demonstrate simple text insertion
536 mxDocText
.setString ( "This is the new body text of the document."
537 + "\n\nThis is on the second line.\n\n" );
539 catch ( Exception e
)
545 // Adding a string at the end or the beginning of text
546 protected void TextRangeExample ()
550 // Get a text range refering to the beginning of the text document
551 XTextRange xStart
= mxDocText
.getStart();
552 // use setString to insert text at the beginning
553 xStart
.setString ( "This is text inserted at the beginning.\n\n" );
554 // Get a text range refering to the end of the text document
555 XTextRange xEnd
= mxDocText
.getEnd();
556 // use setString to insert text at the end
557 xEnd
.setString ( "This is text inserted at the end.\n\n" );
559 catch ( Exception e
)
565 /** moving a text cursor, selecting text and overwriting it
567 protected void TextCursorExample ()
571 // First, get the XSentenceCursor interface of our text cursor
572 XSentenceCursor xSentenceCursor
= (XSentenceCursor
)
573 UnoRuntime
.queryInterface(XSentenceCursor
.class, mxDocCursor
);
574 // Goto the next cursor, without selecting it
575 xSentenceCursor
.gotoNextSentence( false );
576 // Get the XWordCursor interface of our text cursor
577 XWordCursor xWordCursor
= (XWordCursor
) UnoRuntime
.queryInterface(
578 XWordCursor
.class, mxDocCursor
);
579 // Skip the first four words of this sentence and select the fifth
580 xWordCursor
.gotoNextWord( false );
581 xWordCursor
.gotoNextWord( false );
582 xWordCursor
.gotoNextWord( false );
583 xWordCursor
.gotoNextWord( false );
584 xWordCursor
.gotoNextWord( true );
585 // Use the XSimpleText interface to insert a word at the current cursor
586 // location, over-writing the current selection (the fifth word
588 mxDocText
.insertString ( xWordCursor
, "old ", true );
590 // Access the property set of the cursor, and set the currently
591 // selected text (which is the string we just inserted) to be bold
592 XPropertySet xCursorProps
= (XPropertySet
) UnoRuntime
.queryInterface(
593 XPropertySet
.class, mxDocCursor
);
594 xCursorProps
.setPropertyValue ( "CharWeight",
595 new Float(com
.sun
.star
.awt
.FontWeight
.BOLD
) );
597 // replace the '.' at the end of the sentence with a new string
598 xSentenceCursor
.gotoEndOfSentence( false );
599 xWordCursor
.gotoPreviousWord( true );
600 mxDocText
.insertString (xWordCursor
,
601 ", which has been changed with text cursors!",
604 catch ( Exception e
)
610 /** This method inserts both a date field and a user field containing the
613 protected void TextFieldExample ()
617 // Use the text document's factory to create a DateTime text field,
618 // and access it's XTextField interface
619 XTextField xDateField
= (XTextField
) UnoRuntime
.queryInterface (
620 XTextField
.class, mxDocFactory
.createInstance (
621 "com.sun.star.text.TextField.DateTime" ) );
623 // Insert it at the end of the document
624 mxDocText
.insertTextContent ( mxDocText
.getEnd(), xDateField
, false );
626 // Use the text document's factory to create a user text field,
627 // and access it's XDependentTextField interface
628 XDependentTextField xUserField
=
629 (XDependentTextField
) UnoRuntime
.queryInterface (
630 XDependentTextField
.class, mxDocFactory
.createInstance (
631 "com.sun.star.text.TextField.User" ) );
633 // Create a fieldmaster for our newly created User Text field, and
634 // access it's XPropertySet interface
635 XPropertySet xMasterPropSet
= (XPropertySet
)UnoRuntime
.queryInterface(
636 XPropertySet
.class, mxDocFactory
.createInstance (
637 "com.sun.star.text.fieldmaster.User" ) );
639 // Set the name and value of the FieldMaster
640 xMasterPropSet
.setPropertyValue ( "Name", "UserEmperor" );
641 xMasterPropSet
.setPropertyValue ( "Value", new Integer ( 42 ) );
643 // Attach the field master to the user field
644 xUserField
.attachTextFieldMaster ( xMasterPropSet
);
646 // Move the cursor to the end of the document
647 mxDocCursor
.gotoEnd( false );
648 // insert a paragraph break using the XSimpleText interface
649 mxDocText
.insertControlCharacter (
650 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
652 // Insert the user field at the end of the document
653 mxDocText
.insertTextContent ( mxDocText
.getEnd(), xUserField
, false );
655 catch ( Exception e
)
661 /** This method demonstrates how to iterate over paragraphs
663 protected void ParagraphExample ()
667 // The service 'com.sun.star.text.Text' supports the XEnumerationAccess
668 // interface to provide an enumeration of the paragraphs contained by
669 // the text the service refers to.
671 // Here, we access this interface
672 XEnumerationAccess xParaAccess
= (XEnumerationAccess
)
673 UnoRuntime
.queryInterface(XEnumerationAccess
.class, mxDocText
);
674 // Call the XEnumerationAccess's only method to access the actual
676 XEnumeration xParaEnum
= xParaAccess
.createEnumeration();
678 // While there are paragraphs, do things to them
679 while ( xParaEnum
.hasMoreElements() )
681 // Get a reference to the next paragraphs XServiceInfo interface.
682 // TextTables are also part of this enumeration access, so we ask
683 // the element if it is a TextTable, if it doesn't support the
684 // com.sun.star.text.TextTable service, then it is safe to assume
685 // that it really is a paragraph
686 XServiceInfo xInfo
= (XServiceInfo
) UnoRuntime
.queryInterface(
687 XServiceInfo
.class, xParaEnum
.nextElement() );
688 if ( !xInfo
.supportsService ( "com.sun.star.text.TextTable" ) )
690 // Access the paragraph's property set...the properties in this
691 // property set are listed in:
692 // com.sun.star.style.ParagraphProperties
693 XPropertySet xSet
= (XPropertySet
) UnoRuntime
.queryInterface(
694 XPropertySet
.class, xInfo
);
695 // Set the justification to be center justified
696 xSet
.setPropertyValue ( "ParaAdjust",
697 com
.sun
.star
.style
.ParagraphAdjust
.CENTER
);
701 catch ( Exception e
)
707 /** This method returns a random double which isn't too high or too low
709 protected double getRandomDouble ()
711 return ( ( maRandom
.nextInt() % 1000 ) * maRandom
.nextDouble () );
714 /** This method sets the text colour of the cell refered to by sCellName to
715 white and inserts the string sText in it
717 protected static void insertIntoCell(String sCellName
, String sText
,
720 // Access the XText interface of the cell referred to by sCellName
721 XText xCellText
= (XText
) UnoRuntime
.queryInterface(
722 XText
.class, xTable
.getCellByName ( sCellName
) );
724 // create a text cursor from the cells XText interface
725 XTextCursor xCellCursor
= xCellText
.createTextCursor();
726 // Get the property set of the cell's TextCursor
727 XPropertySet xCellCursorProps
= (XPropertySet
)UnoRuntime
.queryInterface(
728 XPropertySet
.class, xCellCursor
);
732 // Set the colour of the text to white
733 xCellCursorProps
.setPropertyValue( "CharColor", new Integer(16777215));
739 // Set the text in the cell to sText
740 xCellText
.setString( sText
);
743 /** This method shows how to create and insert a text table, as well as insert
744 text and formulae into the cells of the table
746 protected void TextTableExample ()
750 // Create a new table from the document's factory
751 XTextTable xTable
= (XTextTable
) UnoRuntime
.queryInterface(
752 XTextTable
.class, mxDocFactory
.createInstance(
753 "com.sun.star.text.TextTable" ) );
755 // Specify that we want the table to have 4 rows and 4 columns
756 xTable
.initialize( 4, 4 );
758 // Insert the table into the document
759 mxDocText
.insertTextContent( mxDocCursor
, xTable
, false);
760 // Get an XIndexAccess of the table rows
761 XIndexAccess xRows
= xTable
.getRows();
763 // Access the property set of the first row (properties listed in
764 // service description: com.sun.star.text.TextTableRow)
765 XPropertySet xRow
= (XPropertySet
) UnoRuntime
.queryInterface(
766 XPropertySet
.class, xRows
.getByIndex ( 0 ) );
767 // If BackTransparant is false, then the background color is visible
768 xRow
.setPropertyValue( "BackTransparent", new Boolean(false));
769 // Specify the color of the background to be dark blue
770 xRow
.setPropertyValue( "BackColor", new Integer(6710932));
772 // Access the property set of the whole table
773 XPropertySet xTableProps
= (XPropertySet
)UnoRuntime
.queryInterface(
774 XPropertySet
.class, xTable
);
775 // We want visible background colors
776 xTableProps
.setPropertyValue( "BackTransparent", new Boolean(false));
777 // Set the background colour to light blue
778 xTableProps
.setPropertyValue( "BackColor", new Integer(13421823));
780 // set the text (and text colour) of all the cells in the first row
782 insertIntoCell( "A1", "First Column", xTable
);
783 insertIntoCell( "B1", "Second Column", xTable
);
784 insertIntoCell( "C1", "Third Column", xTable
);
785 insertIntoCell( "D1", "Results", xTable
);
787 // Insert random numbers into the first this three cells of each
789 xTable
.getCellByName( "A2" ).setValue( getRandomDouble() );
790 xTable
.getCellByName( "B2" ).setValue( getRandomDouble() );
791 xTable
.getCellByName( "C2" ).setValue( getRandomDouble() );
793 xTable
.getCellByName( "A3" ).setValue( getRandomDouble() );
794 xTable
.getCellByName( "B3" ).setValue( getRandomDouble() );
795 xTable
.getCellByName( "C3" ).setValue( getRandomDouble() );
797 xTable
.getCellByName( "A4" ).setValue( getRandomDouble() );
798 xTable
.getCellByName( "B4" ).setValue( getRandomDouble() );
799 xTable
.getCellByName( "C4" ).setValue( getRandomDouble() );
801 // Set the last cell in each row to be a formula that calculates
802 // the sum of the first three cells
803 xTable
.getCellByName( "D2" ).setFormula( "sum <A2:C2>" );
804 xTable
.getCellByName( "D3" ).setFormula( "sum <A3:C3>" );
805 xTable
.getCellByName( "D4" ).setFormula( "sum <A4:C4>" );
812 /** This method shows how to create and manipulate text frames
814 protected void TextFrameExample ()
818 // Use the document's factory to create a new text frame and
819 // immediately access it's XTextFrame interface
820 XTextFrame xFrame
= (XTextFrame
) UnoRuntime
.queryInterface (
821 XTextFrame
.class, mxDocFactory
.createInstance (
822 "com.sun.star.text.TextFrame" ) );
824 // Access the XShape interface of the TextFrame
825 XShape xShape
= (XShape
)UnoRuntime
.queryInterface(XShape
.class, xFrame
);
826 // Access the XPropertySet interface of the TextFrame
827 XPropertySet xFrameProps
= (XPropertySet
)UnoRuntime
.queryInterface(
828 XPropertySet
.class, xFrame
);
830 // Set the size of the new Text Frame using the XShape's 'setSize'
832 Size aSize
= new Size();
835 xShape
.setSize(aSize
);
836 // Set the AnchorType to
837 // com.sun.star.text.TextContentAnchorType.AS_CHARACTER
838 xFrameProps
.setPropertyValue( "AnchorType",
839 TextContentAnchorType
.AS_CHARACTER
);
840 // Go to the end of the text document
841 mxDocCursor
.gotoEnd( false );
842 // Insert a new paragraph
843 mxDocText
.insertControlCharacter (
844 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
845 // Then insert the new frame
846 mxDocText
.insertTextContent(mxDocCursor
, xFrame
, false);
848 // Access the XText interface of the text contained within the frame
849 XText xFrameText
= xFrame
.getText();
850 // Create a TextCursor over the frame's contents
851 XTextCursor xFrameCursor
= xFrameText
.createTextCursor();
852 // Insert some text into the frame
853 xFrameText
.insertString(
854 xFrameCursor
, "The first line in the newly created text frame.",
856 xFrameText
.insertString(
857 xFrameCursor
, "\nThe second line in the new text frame.", false );
858 // Insert a paragraph break into the document (not the frame)
859 mxDocText
.insertControlCharacter (
860 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
868 /** This example demonstrates the use of the AutoTextContainer, AutoTextGroup
869 and AutoTextEntry services and shows how to create, insert and modify
872 protected void AutoTextExample ()
876 // Go to the end of the document
877 mxDocCursor
.gotoEnd( false );
878 // Insert two paragraphs
879 mxDocText
.insertControlCharacter ( mxDocCursor
,
880 ControlCharacter
.PARAGRAPH_BREAK
, false );
881 mxDocText
.insertControlCharacter ( mxDocCursor
,
882 ControlCharacter
.PARAGRAPH_BREAK
, false );
883 // Position the cursor in the second paragraph
884 XParagraphCursor xParaCursor
= (XParagraphCursor
)
885 UnoRuntime
.queryInterface(XParagraphCursor
.class, mxDocCursor
);
886 xParaCursor
.gotoPreviousParagraph ( false );
888 // Get an XNameAccess interface to all auto text groups from the
890 XNameAccess xContainer
= (XNameAccess
) UnoRuntime
.queryInterface(
891 XNameAccess
.class, mxFactory
.createInstance (
892 "com.sun.star.text.AutoTextContainer" ) );
894 // Create a new table at the document factory
895 XTextTable xTable
= (XTextTable
) UnoRuntime
.queryInterface(
896 XTextTable
.class, mxDocFactory
.createInstance(
897 "com.sun.star.text.TextTable" ) );
899 // Store the names of all auto text groups in an array of strings
900 String
[] aGroupNames
= xContainer
.getElementNames();
902 // Make sure we have at least one group name
903 if ( aGroupNames
.length
> 0 )
905 // initialise the table to have a row for every autotext group
906 // in a single column + one additional row for a header
907 xTable
.initialize( aGroupNames
.length
+1,1);
909 // Access the XPropertySet of the table
910 XPropertySet xTableProps
= (XPropertySet
)UnoRuntime
.queryInterface(
911 XPropertySet
.class, xTable
);
913 // We want a visible background
914 xTableProps
.setPropertyValue( "BackTransparent",
917 // We want the background to be light blue
918 xTableProps
.setPropertyValue( "BackColor", new Integer(13421823));
920 // Inser the table into the document
921 mxDocText
.insertTextContent( mxDocCursor
, xTable
, false);
923 // Get an XIndexAccess to all table rows
924 XIndexAccess xRows
= xTable
.getRows();
926 // Get the first row in the table
927 XPropertySet xRow
= (XPropertySet
) UnoRuntime
.queryInterface(
928 XPropertySet
.class, xRows
.getByIndex ( 0 ) );
930 // We want the background of the first row to be visible too
931 xRow
.setPropertyValue( "BackTransparent", new Boolean(false));
933 // And let's make it dark blue
934 xRow
.setPropertyValue( "BackColor", new Integer(6710932));
936 // Put a description of the table contents into the first cell
937 insertIntoCell( "A1", "AutoText Groups", xTable
);
939 // Create a table cursor pointing at the second cell in the first
941 XTextTableCursor xTableCursor
= xTable
.createCursorByCellName("A2");
943 // Loop over the group names
944 for ( int i
= 0 ; i
< aGroupNames
.length
; i
++ )
946 // Get the name of the current cell
947 String sCellName
= xTableCursor
.getRangeName ();
949 // Get the XText interface of the current cell
950 XText xCellText
= (XText
) UnoRuntime
.queryInterface (
951 XText
.class, xTable
.getCellByName ( sCellName
) );
953 // Set the cell contents of the current cell to be
954 //the name of the of an autotext group
955 xCellText
.setString ( aGroupNames
[i
] );
957 // Access the autotext group with this name
958 XAutoTextGroup xGroup
= (XAutoTextGroup
)
959 UnoRuntime
.queryInterface (XAutoTextGroup
.class,
960 xContainer
.getByName(aGroupNames
[i
]));
962 // Get the titles of each autotext block in this group
963 String
[] aBlockNames
= xGroup
.getTitles();
965 // Make sure that the autotext group contains at least one block
966 if ( aBlockNames
.length
> 0 )
968 // Split the current cell vertically into two seperate cells
969 xTableCursor
.splitRange ( (short) 1, false );
971 // Put the cursor in the newly created right hand cell
973 xTableCursor
.goRight ( (short) 1, false );
975 // Split this cell horizontally to make a seperate cell
976 // for each Autotext block
977 if ( ( aBlockNames
.length
-1 ) > 0 )
978 xTableCursor
.splitRange (
979 (short) (aBlockNames
.length
- 1), true );
981 // loop over the block names
982 for ( int j
= 0 ; j
< aBlockNames
.length
; j
++ )
984 // Get the XText interface of the current cell
985 xCellText
= (XText
) UnoRuntime
.queryInterface (
986 XText
.class, xTable
.getCellByName (
987 xTableCursor
.getRangeName() ) );
989 // Set the text contents of the current cell to the
990 // title of an Autotext block
991 xCellText
.setString ( aBlockNames
[j
] );
993 // Move the cursor down one cell
994 xTableCursor
.goDown( (short)1, false);
997 // Go back to the cell we originally split
998 xTableCursor
.gotoCellByName ( sCellName
, false );
1001 xTableCursor
.goDown( (short)1, false);
1004 XAutoTextGroup xGroup
;
1005 String
[] aBlockNames
;
1007 // Add a depth so that we only generate 200 numbers before giving up
1008 // on finding a random autotext group that contains autotext blocks
1012 // Generate a random, positive number which is lower than
1013 // the number of autotext groups
1014 int nRandom
= Math
.abs ( maRandom
.nextInt() %
1015 aGroupNames
.length
);
1017 // Get the autotext group at this name
1018 xGroup
= ( XAutoTextGroup
) UnoRuntime
.queryInterface (
1019 XAutoTextGroup
.class, xContainer
.getByName (
1020 aGroupNames
[ nRandom
] ) );
1022 // Fill our string array with the names of all the blocks in
1024 aBlockNames
= xGroup
.getElementNames();
1026 // increment our depth counter
1029 while ( nDepth
< 200 && aBlockNames
.length
== 0 );
1030 // If we managed to find a group containg blocks...
1031 if ( aBlockNames
.length
> 0 )
1033 // Pick a random block in this group and get it's
1034 // XAutoTextEntry interface
1035 int nRandom
= Math
.abs ( maRandom
.nextInt()
1036 % aBlockNames
.length
);
1037 XAutoTextEntry xEntry
= ( XAutoTextEntry
)
1038 UnoRuntime
.queryInterface (
1039 XAutoTextEntry
.class, xGroup
.getByName (
1040 aBlockNames
[ nRandom
] ) );
1041 // insert the modified autotext block at the end of the document
1042 xEntry
.applyTo ( mxDocCursor
);
1044 // Get the titles of all text blocks in this AutoText group
1045 String
[] aBlockTitles
= xGroup
.getTitles();
1047 // Get the XNamed interface of the autotext group
1048 XNamed xGroupNamed
= ( XNamed
) UnoRuntime
.queryInterface (
1049 XNamed
.class, xGroup
);
1051 // Output the short cut and title of the random block
1052 //and the name of the group it's from
1053 System
.out
.println ( "Inserted the Autotext '" +
1054 aBlockTitles
[nRandom
]
1055 + "', shortcut '" + aBlockNames
[nRandom
]
1057 + xGroupNamed
.getName());
1061 // Go to the end of the document
1062 mxDocCursor
.gotoEnd( false );
1063 // Insert new paragraph
1064 mxDocText
.insertControlCharacter (
1065 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1067 // Position cursor in new paragraph
1068 xParaCursor
.gotoPreviousParagraph ( false );
1070 // Insert a string in the new paragraph
1071 mxDocText
.insertString ( mxDocCursor
,
1072 "Some text for a new autotext block", false );
1074 // Go to the end of the document
1075 mxDocCursor
.gotoEnd( false );
1079 e
.printStackTrace();
1083 /** This method demonstrates how to insert indexes and index marks
1085 protected void IndexExample ()
1089 // Go to the end of the document
1090 mxDocCursor
.gotoEnd( false );
1091 // Insert a new paragraph and position the cursor in it
1092 mxDocText
.insertControlCharacter ( mxDocCursor
,
1093 ControlCharacter
.PARAGRAPH_BREAK
, false );
1094 XParagraphCursor xParaCursor
= (XParagraphCursor
)
1095 UnoRuntime
.queryInterface( XParagraphCursor
.class, mxDocCursor
);
1096 xParaCursor
.gotoPreviousParagraph ( false );
1098 // Create a new ContentIndexMark and get it's XPropertySet interface
1099 XPropertySet xEntry
= (XPropertySet
)UnoRuntime
.queryInterface(
1101 mxDocFactory
.createInstance("com.sun.star.text.ContentIndexMark"));
1103 // Set the text to be displayed in the index
1104 xEntry
.setPropertyValue(
1105 "AlternativeText", "Big dogs! Falling on my head!");
1107 // The Level property _must_ be set
1108 xEntry
.setPropertyValue ( "Level", new Short ( (short) 1 ) );
1110 // Create a ContentIndex and access it's XPropertySet interface
1111 XPropertySet xIndex
= (XPropertySet
) UnoRuntime
.queryInterface(
1113 mxDocFactory
.createInstance ( "com.sun.star.text.ContentIndex" ) );
1115 // Again, the Level property _must_ be set
1116 xIndex
.setPropertyValue ( "Level", new Short ( (short) 10 ) );
1118 // Access the XTextContent interfaces of both the Index and the
1120 XTextContent xIndexContent
= (XTextContent
) UnoRuntime
.queryInterface(
1121 XTextContent
.class, xIndex
);
1122 XTextContent xEntryContent
= (XTextContent
) UnoRuntime
.queryInterface(
1123 XTextContent
.class, xEntry
);
1125 // Insert both in the document
1126 mxDocText
.insertTextContent ( mxDocCursor
, xEntryContent
, false );
1127 mxDocText
.insertTextContent ( mxDocCursor
, xIndexContent
, false );
1129 // Get the XDocumentIndex interface of the Index
1130 XDocumentIndex xDocIndex
= (XDocumentIndex
) UnoRuntime
.queryInterface(
1131 XDocumentIndex
.class, xIndex
);
1133 // And call it's update method
1138 e
.printStackTrace();
1142 /** This method demonstrates how to create and insert reference marks, and
1143 * GetReference Text Fields
1145 protected void ReferenceExample ()
1149 // Go to the end of the document
1150 mxDocCursor
.gotoEnd( false );
1152 // Insert a paragraph break
1153 mxDocText
.insertControlCharacter (
1154 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1156 // Get the Paragraph cursor
1157 XParagraphCursor xParaCursor
= (XParagraphCursor
)
1158 UnoRuntime
.queryInterface( XParagraphCursor
.class, mxDocCursor
);
1160 // Move the cursor into the new paragraph
1161 xParaCursor
.gotoPreviousParagraph ( false );
1163 // Create a new ReferenceMark and get it's XNamed interface
1164 XNamed xRefMark
= (XNamed
) UnoRuntime
.queryInterface(XNamed
.class,
1165 mxDocFactory
.createInstance ("com.sun.star.text.ReferenceMark"));
1167 // Set the name to TableHeader
1168 xRefMark
.setName ( "TableHeader" );
1170 // Get the TextTablesSupplier interface of the document
1171 XTextTablesSupplier xTableSupplier
= ( XTextTablesSupplier
)
1172 UnoRuntime
.queryInterface(XTextTablesSupplier
.class, mxDoc
);
1174 // Get an XIndexAccess of TextTables
1175 XIndexAccess xTables
= (XIndexAccess
)UnoRuntime
.queryInterface(
1176 XIndexAccess
.class, xTableSupplier
.getTextTables());
1178 // We've only inserted one table, so get the first one from index zero
1179 XTextTable xTable
= ( XTextTable
) UnoRuntime
.queryInterface (
1180 XTextTable
.class, xTables
.getByIndex( 0 ) );
1182 // Get the first cell from the table
1183 XText xTableText
= (XText
) UnoRuntime
.queryInterface(
1184 XText
.class, xTable
.getCellByName ( "A1" ) );
1186 // Get a text cursor for the first cell
1187 XTextCursor xTableCursor
= xTableText
.createTextCursor();
1189 // Get the XTextContent interface of the reference mark so we can
1191 XTextContent xContent
= ( XTextContent
) UnoRuntime
.queryInterface (
1192 XTextContent
.class, xRefMark
);
1194 // Insert the reference mark into the first cell of the table
1195 xTableText
.insertTextContent ( xTableCursor
, xContent
, false );
1197 // Create a 'GetReference' text field to refer to the reference mark
1198 // we just inserted, and get it's XPropertySet interface
1199 XPropertySet xFieldProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1200 XPropertySet
.class, mxDocFactory
.createInstance (
1201 "com.sun.star.text.TextField.GetReference" ) );
1203 // Get the XReferenceMarksSupplier interface of the document
1204 XReferenceMarksSupplier xRefSupplier
= ( XReferenceMarksSupplier
)
1205 UnoRuntime
.queryInterface( XReferenceMarksSupplier
.class, mxDoc
);
1207 // Get an XNameAccess which refers to all inserted reference marks
1208 XNameAccess xMarks
= ( XNameAccess
) UnoRuntime
.queryInterface (
1209 XNameAccess
.class, xRefSupplier
.getReferenceMarks() );
1211 // Put the names of each reference mark into an array of strings
1212 String
[] aNames
= xMarks
.getElementNames();
1214 // Make sure that at least 1 reference mark actually exists
1215 // (well, we just inserted one!)
1216 if ( aNames
.length
> 0 )
1218 // Output the name of the first reference mark ('TableHeader')
1219 System
.out
.println (
1220 "GetReference text field inserted for ReferenceMark : "
1223 // Set the SourceName of the GetReference text field to
1225 xFieldProps
.setPropertyValue ( "SourceName", aNames
[0] );
1227 // specify that the source is a reference mark (could also be a
1228 // footnote, bookmark or sequence field )
1229 xFieldProps
.setPropertyValue ( "ReferenceFieldSource",
1230 new Short(ReferenceFieldSource
.REFERENCE_MARK
));
1232 // We want the reference displayed as 'above' or 'below'
1233 xFieldProps
.setPropertyValue ( "ReferenceFieldPart",
1234 new Short(ReferenceFieldPart
.UP_DOWN
));
1237 // Get the XTextContent interface of the GetReference text field
1238 XTextContent xRefContent
= (XTextContent
) UnoRuntime
.queryInterface(
1239 XTextContent
.class, xFieldProps
);
1241 // Go to the end of the document
1242 mxDocCursor
.gotoEnd( false );
1244 // Make some text to precede the reference
1245 mxDocText
.insertString(mxDocText
.getEnd(), "The table ", false);
1247 // Insert the text field
1248 mxDocText
.insertTextContent(mxDocText
.getEnd(), xRefContent
, false);
1250 // And some text after the reference..
1251 mxDocText
.insertString(mxDocText
.getEnd(),
1252 " contains the sum of some random numbers.", false );
1254 // Refresh the document
1255 XRefreshable xRefresh
= (XRefreshable
) UnoRuntime
.queryInterface(
1256 XRefreshable
.class, mxDoc
);
1262 e
.printStackTrace();
1266 /** This method demonstrates how to create and insert footnotes, and how to
1267 access the XFootnotesSupplier interface of the document
1269 protected void FootnoteExample ()
1273 // Create a new footnote from the document factory and get it's
1274 // XFootnote interface
1275 XFootnote xFootnote
= (XFootnote
) UnoRuntime
.queryInterface(
1276 XFootnote
.class, mxDocFactory
.createInstance (
1277 "com.sun.star.text.Footnote" ) );
1279 // Set the label to 'Numbers'
1280 xFootnote
.setLabel ( "Numbers" );
1282 // Get the footnotes XTextContent interface so we can...
1283 XTextContent xContent
= ( XTextContent
) UnoRuntime
.queryInterface (
1284 XTextContent
.class, xFootnote
);
1286 // ...insert it into the document
1287 mxDocText
.insertTextContent ( mxDocCursor
, xContent
, false );
1289 // Get the XFootnotesSupplier interface of the document
1290 XFootnotesSupplier xFootnoteSupplier
= (XFootnotesSupplier
)
1291 UnoRuntime
.queryInterface(XFootnotesSupplier
.class, mxDoc
);
1293 // Get an XIndexAccess interface to all footnotes
1294 XIndexAccess xFootnotes
= ( XIndexAccess
) UnoRuntime
.queryInterface (
1295 XIndexAccess
.class, xFootnoteSupplier
.getFootnotes() );
1297 // Get the XFootnote interface to the first footnote inserted ('Numbers')
1298 XFootnote xNumbers
= ( XFootnote
) UnoRuntime
.queryInterface (
1299 XFootnote
.class, xFootnotes
.getByIndex( 0 ) );
1301 // Get the XSimpleText interface to the Footnote
1302 XSimpleText xSimple
= (XSimpleText
) UnoRuntime
.queryInterface (
1303 XSimpleText
.class, xNumbers
);
1305 // Create a text cursor for the foot note text
1306 XTextRange xRange
= (XTextRange
) UnoRuntime
.queryInterface (
1307 XTextRange
.class, xSimple
.createTextCursor() );
1309 // And insert the actual text of the footnote.
1310 xSimple
.insertString (
1311 xRange
, " The numbers were generated by using java.util.Random", false );
1315 e
.printStackTrace();
1319 /** This method demonstrates how to create and manipulate shapes, and how to
1320 access the draw page of the document to insert shapes
1322 protected void DrawPageExample ()
1326 // Go to the end of the document
1327 mxDocCursor
.gotoEnd( false );
1328 // Insert two new paragraphs
1329 mxDocText
.insertControlCharacter(mxDocCursor
,
1330 ControlCharacter
.PARAGRAPH_BREAK
, false);
1331 mxDocText
.insertControlCharacter(mxDocCursor
,
1332 ControlCharacter
.PARAGRAPH_BREAK
, false);
1334 // Get the XParagraphCursor interface of our document cursor
1335 XParagraphCursor xParaCursor
= (XParagraphCursor
)
1336 UnoRuntime
.queryInterface( XParagraphCursor
.class, mxDocCursor
);
1338 // Position the cursor in the 2nd paragraph
1339 xParaCursor
.gotoPreviousParagraph ( false );
1341 // Create a RectangleShape using the document factory
1342 XShape xRect
= (XShape
) UnoRuntime
.queryInterface(
1343 XShape
.class, mxDocFactory
.createInstance (
1344 "com.sun.star.drawing.RectangleShape" ) );
1346 // Create an EllipseShape using the document factory
1347 XShape xEllipse
= (XShape
) UnoRuntime
.queryInterface(
1348 XShape
.class, mxDocFactory
.createInstance (
1349 "com.sun.star.drawing.EllipseShape" ) );
1351 // Set the size of both the ellipse and the rectangle
1352 Size aSize
= new Size();
1353 aSize
.Height
= 4000;
1354 aSize
.Width
= 10000;
1355 xRect
.setSize(aSize
);
1356 aSize
.Height
= 3000;
1358 xEllipse
.setSize ( aSize
);
1360 // Set the position of the Rectangle to the right of the ellipse
1361 Point aPoint
= new Point();
1364 xRect
.setPosition ( aPoint
);
1366 // Get the XPropertySet interfaces of both shapes
1367 XPropertySet xRectProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1368 XPropertySet
.class, xRect
);
1369 XPropertySet xEllipseProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1370 XPropertySet
.class, xEllipse
);
1372 // And set the AnchorTypes of both shapes to 'AT_PARAGRAPH'
1373 xRectProps
.setPropertyValue ( "AnchorType",
1374 TextContentAnchorType
.AT_PARAGRAPH
);
1375 xEllipseProps
.setPropertyValue ( "AnchorType",
1376 TextContentAnchorType
.AT_PARAGRAPH
);
1378 // Access the XDrawPageSupplier interface of the document
1379 XDrawPageSupplier xDrawPageSupplier
= (XDrawPageSupplier
)
1380 UnoRuntime
.queryInterface (XDrawPageSupplier
.class, mxDoc
);
1382 // Get the XShapes interface of the draw page
1383 XShapes xShapes
= ( XShapes
) UnoRuntime
.queryInterface (
1384 XShapes
.class, xDrawPageSupplier
.getDrawPage () );
1387 xShapes
.add ( xEllipse
);
1388 xShapes
.add ( xRect
);
1391 This doesn't work, I am assured that FME and AMA are fixing it.
1393 XShapes xGrouper = (XShapes) UnoRuntime.queryInterface(
1394 XShapes.class, mxDocFactory.createInstance (
1395 "com.sun.star.drawing.GroupShape" ) );
1397 XShape xGrouperShape = (XShape) UnoRuntime.queryInterface(
1398 XShape.class, xGrouper );
1399 xShapes.add ( xGrouperShape );
1401 xGrouper.add ( xRect );
1402 xGrouper.add ( xEllipse );
1404 XShapeGrouper xShapeGrouper = (XShapeGrouper)
1405 UnoRuntime.queryInterface(XShapeGrouper.class, xShapes);
1406 xShapeGrouper.group ( xGrouper );
1412 e
.printStackTrace();
1416 /** This method demonstrates how to create, insert and apply styles
1418 protected void StylesExample ()
1422 // Go to the end of the document
1423 mxDocCursor
.gotoEnd( false );
1425 // Insert two paragraph breaks
1426 mxDocText
.insertControlCharacter (
1427 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1428 mxDocText
.insertControlCharacter (
1429 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1431 // Create a new style from the document's factory
1432 XStyle xStyle
= (XStyle
) UnoRuntime
.queryInterface(
1433 XStyle
.class, mxDocFactory
.createInstance(
1434 "com.sun.star.style.ParagraphStyle" ) );
1436 // Access the XPropertySet interface of the new style
1437 XPropertySet xStyleProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1438 XPropertySet
.class, xStyle
);
1440 // Give the new style a light blue background
1441 xStyleProps
.setPropertyValue ( "ParaBackColor", new Integer (13421823));
1443 // Get the StyleFamiliesSupplier interface of the document
1444 XStyleFamiliesSupplier xSupplier
= (XStyleFamiliesSupplier
)
1445 UnoRuntime
.queryInterface(XStyleFamiliesSupplier
.class, mxDoc
);
1447 // Use the StyleFamiliesSupplier interface to get the XNameAccess
1448 // interface of the actual style families
1449 XNameAccess xFamilies
= ( XNameAccess
) UnoRuntime
.queryInterface (
1450 XNameAccess
.class, xSupplier
.getStyleFamilies() );
1452 // Access the 'ParagraphStyles' Family
1453 XNameContainer xFamily
= (XNameContainer
) UnoRuntime
.queryInterface (
1454 XNameContainer
.class,
1455 xFamilies
.getByName ( "ParagraphStyles" ) );
1457 // Insert the newly created style into the ParagraphStyles family
1458 xFamily
.insertByName ( "All-Singing All-Dancing Style", xStyle
);
1460 // Get the XParagraphCursor interface of the document cursor
1461 XParagraphCursor xParaCursor
= (XParagraphCursor
)
1462 UnoRuntime
.queryInterface( XParagraphCursor
.class, mxDocCursor
);
1464 // Select the first paragraph inserted
1465 xParaCursor
.gotoPreviousParagraph ( false );
1466 xParaCursor
.gotoPreviousParagraph ( true );
1468 // Access the property set of the cursor selection
1469 XPropertySet xCursorProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1470 XPropertySet
.class, mxDocCursor
);
1472 // Set the style of the cursor selection to our newly created style
1473 xCursorProps
.setPropertyValue ( "ParaStyleName",
1474 "All-Singing All-Dancing Style" );
1476 // Go back to the end
1477 mxDocCursor
.gotoEnd ( false );
1479 // Select the last paragraph in the document
1480 xParaCursor
.gotoNextParagraph ( true );
1482 // And reset it's style to 'Standard' (the programmatic name for
1483 // the default style)
1484 xCursorProps
.setPropertyValue ( "ParaStyleName", "Standard" );
1488 e
.printStackTrace();
1492 /** This method demonstrates how to set numbering types and numbering levels
1493 using the com.sun.star.text.NumberingRules service
1495 protected void NumberingExample ()
1499 // Go to the end of the document
1500 mxDocCursor
.gotoEnd( false );
1501 // Get the RelativeTextContentInsert interface of the document
1502 XRelativeTextContentInsert xRelative
=
1503 (XRelativeTextContentInsert
) UnoRuntime
.queryInterface (
1504 XRelativeTextContentInsert
.class, mxDocText
);
1506 // Use the document's factory to create the NumberingRules service,
1507 // and get it's XIndexAccess interface
1508 XIndexAccess xNum
= (XIndexAccess
) UnoRuntime
.queryInterface(
1510 mxDocFactory
.createInstance( "com.sun.star.text.NumberingRules" ) );
1512 // Also get the NumberingRule's XIndexReplace interface
1513 XIndexReplace xReplace
= (XIndexReplace
) UnoRuntime
.queryInterface(
1514 XIndexReplace
.class, xNum
);
1516 // Create an array of XPropertySets, one for each of the three
1517 // paragraphs we're about to create
1518 XPropertySet xParas
[] = new XPropertySet
[ 3 ];
1519 for ( int i
= 0 ; i
< 3 ; ++ i
)
1521 // Create a new paragraph
1522 XTextContent xNewPara
= (XTextContent
) UnoRuntime
.queryInterface(
1523 XTextContent
.class, mxDocFactory
.createInstance(
1524 "com.sun.star.text.Paragraph" ) );
1526 // Get the XPropertySet interface of the new paragraph and put
1528 xParas
[i
] = (XPropertySet
) UnoRuntime
.queryInterface(
1529 XPropertySet
.class, xNewPara
);
1531 // Insert the new paragraph into the document after the fish
1532 // section. As it is an insert relative to the fish section, the
1533 // first paragraph inserted will be below the next two
1534 xRelative
.insertTextContentAfter ( xNewPara
, mxFishSection
);
1536 // Separate from the above, but also needs to be done three times
1538 // Get the PropertyValue sequence for this numbering level
1539 PropertyValue
[] aProps
= (PropertyValue
[] ) xNum
.getByIndex ( i
);
1541 // Iterate over the PropertyValue's for this numbering level,
1542 // looking for the 'NumberingType' property
1543 for ( int j
= 0 ; j
< aProps
.length
; ++j
)
1545 if ( aProps
[j
].Name
.equals ( "NumberingType" ) )
1547 // Once we find it, set it's value to a new type,
1548 // dependent on which numbering level we're currently on
1551 case 0 : aProps
[j
].Value
=
1552 new Short(NumberingType
.ROMAN_UPPER
);
1554 case 1 : aProps
[j
].Value
=
1555 new Short(NumberingType
.CHARS_UPPER_LETTER
);
1557 case 2 : aProps
[j
].Value
=
1558 new Short(NumberingType
.ARABIC
);
1561 // Put the updated PropertyValue sequence back into the
1562 // NumberingRules service
1563 xReplace
.replaceByIndex ( i
, aProps
);
1568 // Get the XParagraphCursor interface of our text cursro
1569 XParagraphCursor xParaCursor
= (XParagraphCursor
)
1570 UnoRuntime
.queryInterface( XParagraphCursor
.class, mxDocCursor
);
1571 // Go to the end of the document, then select the preceding paragraphs
1572 mxDocCursor
.gotoEnd ( false );
1573 xParaCursor
.gotoPreviousParagraph ( false );
1574 xParaCursor
.gotoPreviousParagraph ( true );
1575 xParaCursor
.gotoPreviousParagraph ( true );
1577 // Get the XPropertySet of the cursor's currently selected text
1578 XPropertySet xCursorProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1579 XPropertySet
.class, mxDocCursor
);
1581 // Set the updated Numbering rules to the cursor's property set
1582 xCursorProps
.setPropertyValue ( "NumberingRules", xNum
);
1583 mxDocCursor
.gotoEnd( false );
1585 // Set the first paragraph that was inserted to a numbering level of
1586 // 2 (thus it will have Arabic style numbering)
1587 xParas
[0].setPropertyValue ( "NumberingLevel", new Short((short) 2));
1589 // Set the second paragraph that was inserted to a numbering level of
1590 // 1 (thus it will have 'Chars Upper Letter' style numbering)
1591 xParas
[1].setPropertyValue ( "NumberingLevel", new Short((short) 1));
1593 // Set the third paragraph that was inserted to a numbering level of
1594 // 0 (thus it will have 'Chars Upper Letter' style numbering)
1595 xParas
[2].setPropertyValue ( "NumberingLevel", new Short((short) 0));
1599 e
.printStackTrace();
1603 /** This method demonstrates how to create linked and unlinked sections
1605 protected void TextSectionExample ()
1609 // Go to the end of the document
1610 mxDocCursor
.gotoEnd( false );
1611 // Insert two paragraph breaks
1612 mxDocText
.insertControlCharacter (
1613 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1614 mxDocText
.insertControlCharacter (
1615 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, true );
1617 // Create a new TextSection from the document factory and access
1618 // it's XNamed interface
1619 XNamed xChildNamed
= (XNamed
) UnoRuntime
.queryInterface(
1620 XNamed
.class, mxDocFactory
.createInstance(
1621 "com.sun.star.text.TextSection" ) );
1622 // Set the new sections name to 'Child_Section'
1623 xChildNamed
.setName ( "Child_Section" );
1625 // Access the Child_Section's XTextContent interface and insert it
1626 // into the document
1627 XTextContent xChildSection
= (XTextContent
) UnoRuntime
.queryInterface(
1628 XTextContent
.class, xChildNamed
);
1629 mxDocText
.insertTextContent ( mxDocCursor
, xChildSection
, false );
1631 // Access the XParagraphCursor interface of our text cursor
1632 XParagraphCursor xParaCursor
= (XParagraphCursor
)
1633 UnoRuntime
.queryInterface(XParagraphCursor
.class, mxDocCursor
);
1635 // Go back one paragraph (into Child_Section)
1636 xParaCursor
.gotoPreviousParagraph ( false );
1638 // Insert a string into the Child_Section
1639 mxDocText
.insertString ( mxDocCursor
, "This is a test", false );
1641 // Go to the end of the document
1642 mxDocCursor
.gotoEnd( false );
1644 // Go back two paragraphs
1645 xParaCursor
.gotoPreviousParagraph ( false );
1646 xParaCursor
.gotoPreviousParagraph ( false );
1647 // Go to the end of the document, selecting the two paragraphs
1648 mxDocCursor
.gotoEnd ( true );
1650 // Create another text section and access it's XNamed interface
1651 XNamed xParentNamed
= (XNamed
) UnoRuntime
.queryInterface(XNamed
.class,
1652 mxDocFactory
.createInstance("com.sun.star.text.TextSection"));
1654 // Set this text section's name to Parent_Section
1655 xParentNamed
.setName ( "Parent_Section" );
1657 // Access the Parent_Section's XTextContent interface ...
1658 XTextContent xParentSection
= (XTextContent
) UnoRuntime
.queryInterface(
1659 XTextContent
.class, xParentNamed
);
1660 // ...and insert it into the document
1661 mxDocText
.insertTextContent ( mxDocCursor
, xParentSection
, false );
1663 // Go to the end of the document
1664 mxDocCursor
.gotoEnd ( false );
1665 // Insert a new paragraph
1666 mxDocText
.insertControlCharacter (
1667 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1668 // And select the new pargraph
1669 xParaCursor
.gotoPreviousParagraph ( true );
1671 // Create a new Text Section and access it's XNamed interface
1672 XNamed xLinkNamed
= (XNamed
) UnoRuntime
.queryInterface(XNamed
.class,
1673 mxDocFactory
.createInstance("com.sun.star.text.TextSection"));
1674 // Set the new text section's name to Linked_Section
1675 xLinkNamed
.setName ( "Linked_Section" );
1677 // Access the Linked_Section's XTextContent interface
1678 XTextContent xLinkedSection
= (XTextContent
) UnoRuntime
.queryInterface(
1679 XTextContent
.class, xLinkNamed
);
1680 // And insert the Linked_Section into the document
1681 mxDocText
.insertTextContent ( mxDocCursor
, xLinkedSection
, false );
1683 // Access the Linked_Section's XPropertySet interface
1684 XPropertySet xLinkProps
= (XPropertySet
)UnoRuntime
.queryInterface(
1685 XPropertySet
.class, xLinkNamed
);
1686 // Set the linked section to be linked to the Child_Section
1687 xLinkProps
.setPropertyValue ( "LinkRegion", "Child_Section" );
1689 // Access the XPropertySet interface of the Child_Section
1690 XPropertySet xChildProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1691 XPropertySet
.class, xChildNamed
);
1692 // Set the Child_Section's background colour to blue
1693 xChildProps
.setPropertyValue( "BackColor", new Integer(13421823));
1695 // Refresh the document, so the linked section matches the Child_Section
1696 XRefreshable xRefresh
= (XRefreshable
) UnoRuntime
.queryInterface(
1697 XRefreshable
.class, mxDoc
);
1702 e
.printStackTrace();
1706 /** This method demonstrates the XTextColumns interface and how to insert a
1707 blank paragraph using the XRelativeTextContentInsert interface
1709 protected void TextColumnsExample ()
1713 // Go to the end of the doucment
1714 mxDocCursor
.gotoEnd( false );
1715 // insert a new paragraph
1716 mxDocText
.insertControlCharacter (
1717 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1719 // insert the string 'I am a fish.' 100 times
1720 for ( int i
= 0 ; i
< 100 ; ++i
)
1722 mxDocText
.insertString ( mxDocCursor
, "I am a fish.", false );
1724 // insert a paragraph break after the text
1725 mxDocText
.insertControlCharacter (
1726 mxDocCursor
, ControlCharacter
.PARAGRAPH_BREAK
, false );
1728 // Get the XParagraphCursor interface of our text cursor
1729 XParagraphCursor xParaCursor
= (XParagraphCursor
)
1730 UnoRuntime
.queryInterface( XParagraphCursor
.class, mxDocCursor
);
1731 // Jump back before all the text we just inserted
1732 xParaCursor
.gotoPreviousParagraph ( false );
1733 xParaCursor
.gotoPreviousParagraph ( false );
1735 // Insert a string at the beginning of the block of text
1736 mxDocText
.insertString ( mxDocCursor
, "Fish section begins:", false );
1738 // Then select all of the text
1739 xParaCursor
.gotoNextParagraph ( true );
1740 xParaCursor
.gotoNextParagraph ( true );
1742 // Create a new text section and get it's XNamed interface
1743 XNamed xSectionNamed
= (XNamed
) UnoRuntime
.queryInterface(XNamed
.class,
1744 mxDocFactory
.createInstance("com.sun.star.text.TextSection"));
1746 // Set the name of our new section (appropiately) to 'Fish'
1747 xSectionNamed
.setName ( "Fish" );
1749 // Create the TextColumns service and get it's XTextColumns interface
1750 XTextColumns xColumns
= (XTextColumns
) UnoRuntime
.queryInterface(
1752 mxDocFactory
.createInstance ( "com.sun.star.text.TextColumns" ) );
1754 // We want three columns
1755 xColumns
.setColumnCount ( (short) 3 );
1757 // Get the TextColumns, and make the middle one narrow with a larger
1758 // margin on the left than the right
1759 TextColumn
[] aSequence
= xColumns
.getColumns ();
1760 aSequence
[1].Width
/= 2;
1761 aSequence
[1].LeftMargin
= 350;
1762 aSequence
[1].RightMargin
= 200;
1763 // Set the updated TextColumns back to the XTextColumns
1764 xColumns
.setColumns ( aSequence
);
1766 // Get the property set interface of our 'Fish' section
1767 XPropertySet xSectionProps
= (XPropertySet
) UnoRuntime
.queryInterface(
1768 XPropertySet
.class, xSectionNamed
);
1770 // Set the columns to the Text Section
1771 xSectionProps
.setPropertyValue ( "TextColumns", xColumns
);
1773 // Get the XTextContent interface of our 'Fish' section
1774 mxFishSection
= (XTextContent
) UnoRuntime
.queryInterface(
1775 XTextContent
.class, xSectionNamed
);
1777 // Insert the 'Fish' section over the currently selected text
1778 mxDocText
.insertTextContent ( mxDocCursor
, mxFishSection
, true );
1780 // Get the wonderful XRelativeTextContentInsert interface
1781 XRelativeTextContentInsert xRelative
= (XRelativeTextContentInsert
)
1782 UnoRuntime
.queryInterface (
1783 XRelativeTextContentInsert
.class, mxDocText
);
1785 // Create a new empty paragraph and get it's XTextContent interface
1786 XTextContent xNewPara
= (XTextContent
) UnoRuntime
.queryInterface(
1788 mxDocFactory
.createInstance("com.sun.star.text.Paragraph"));
1790 // Insert the empty paragraph after the fish Text Section
1791 xRelative
.insertTextContentAfter ( xNewPara
, mxFishSection
);
1795 e
.printStackTrace();