Version 6.4.0.0.beta1, tag libreoffice-6.4.0.0.beta1
[LibreOffice.git] / odk / examples / DevelopersGuide / Text / TextDocuments.java
blob20e9f7a58e724a97af117ace08966f5416c47f5b
1 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*************************************************************************
4 * The Contents of this file are made available subject to the terms of
5 * the BSD license.
7 * Copyright 2000, 2010 Oracle and/or its affiliates.
8 * All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of Sun Microsystems, Inc. nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
29 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
31 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
32 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 *************************************************************************/
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.Random;
40 import com.sun.star.awt.Point;
41 import com.sun.star.awt.Size;
42 import com.sun.star.beans.PropertyValue;
43 import com.sun.star.beans.XPropertySet;
44 import com.sun.star.container.XEnumeration;
45 import com.sun.star.container.XEnumerationAccess;
46 import com.sun.star.container.XIndexAccess;
47 import com.sun.star.container.XIndexReplace;
48 import com.sun.star.container.XNameAccess;
49 import com.sun.star.container.XNameContainer;
50 import com.sun.star.container.XNamed;
51 import com.sun.star.drawing.XDrawPageSupplier;
52 import com.sun.star.drawing.XShape;
53 import com.sun.star.drawing.XShapes;
54 import com.sun.star.frame.XComponentLoader;
55 import com.sun.star.frame.XController;
56 import com.sun.star.frame.XDesktop;
57 import com.sun.star.frame.XModel;
58 import com.sun.star.frame.XStorable;
59 import com.sun.star.lang.XComponent;
60 import com.sun.star.lang.XMultiComponentFactory;
61 import com.sun.star.lang.XMultiServiceFactory;
62 import com.sun.star.lang.XServiceInfo;
63 import com.sun.star.style.NumberingType;
64 import com.sun.star.style.XStyle;
65 import com.sun.star.style.XStyleFamiliesSupplier;
66 import com.sun.star.text.ControlCharacter;
67 import com.sun.star.text.ReferenceFieldPart;
68 import com.sun.star.text.ReferenceFieldSource;
69 import com.sun.star.text.TextColumn;
70 import com.sun.star.text.TextContentAnchorType;
71 import com.sun.star.text.XAutoTextEntry;
72 import com.sun.star.text.XAutoTextGroup;
73 import com.sun.star.text.XBookmarksSupplier;
74 import com.sun.star.text.XDependentTextField;
75 import com.sun.star.text.XDocumentIndex;
76 import com.sun.star.text.XFootnote;
77 import com.sun.star.text.XFootnotesSupplier;
78 import com.sun.star.text.XPageCursor;
79 import com.sun.star.text.XParagraphCursor;
80 import com.sun.star.text.XReferenceMarksSupplier;
81 import com.sun.star.text.XRelativeTextContentInsert;
82 import com.sun.star.text.XSentenceCursor;
83 import com.sun.star.text.XSimpleText;
84 import com.sun.star.text.XText;
85 import com.sun.star.text.XTextColumns;
86 import com.sun.star.text.XTextContent;
87 import com.sun.star.text.XTextCursor;
88 import com.sun.star.text.XTextDocument;
89 import com.sun.star.text.XTextField;
90 import com.sun.star.text.XTextFieldsSupplier;
91 import com.sun.star.text.XTextFrame;
92 import com.sun.star.text.XTextRange;
93 import com.sun.star.text.XTextTable;
94 import com.sun.star.text.XTextTableCursor;
95 import com.sun.star.text.XTextTablesSupplier;
96 import com.sun.star.text.XTextViewCursor;
97 import com.sun.star.text.XTextViewCursorSupplier;
98 import com.sun.star.text.XWordCursor;
99 import com.sun.star.uno.UnoRuntime;
100 import com.sun.star.uno.XComponentContext;
101 import com.sun.star.util.XRefreshable;
102 import com.sun.star.view.XPrintable;
105 public class TextDocuments {
106 // adjust these constant to your local printer!
107 private static String sOutputDir;
109 private static final String aPrinterName = "\\\\so-print\\xml3sof";
111 private XComponentContext mxRemoteContext = null;
112 private XMultiComponentFactory mxRemoteServiceManager = null;
113 private XTextDocument mxDoc = null;
114 private XMultiServiceFactory mxDocFactory = null;
115 private XMultiServiceFactory mxFactory = null;
116 private XText mxDocText = null;
117 private XTextCursor mxDocCursor = null;
118 private XTextContent mxFishSection = null;
119 private Random maRandom = null;
122 * @param args the command line arguments
124 public static void main(String[] args) {
125 TextDocuments textDocuments1 = new TextDocuments();
126 try {
127 // output directory for store test;
128 sOutputDir = args[0];
130 textDocuments1.runDemo();
131 } catch (java.lang.Exception e) {
132 System.out.println(e.getMessage());
133 e.printStackTrace();
134 } finally {
135 System.exit(0);
139 protected void runDemo() throws java.lang.Exception {
140 storePrintExample(); // depends on printer name
141 templateExample();
142 viewCursorExample(); // makes changes to the current document,
143 // use with care
144 editingExample();
147 /** Sample for use of templates
148 * This sample uses the file TextTemplateWithUserFields.odt from the Samples
149 * folder. The file contains a number of User text fields (Variables - User)
150 * and a bookmark which we use to fill in various values
152 protected void templateExample() throws java.lang.Exception {
153 // create a small hashtable that simulates a rowset
154 HashMap<String,String> recipient = new HashMap<String,String>();
155 recipient.put("Company", "Manatee Books");
156 recipient.put("Contact", "Rod Martin");
157 recipient.put("ZIP", "34567");
158 recipient.put("City", "Fort Lauderdale");
159 recipient.put("State", "Florida");
161 // load template with User fields and bookmark
162 java.io.File sourceFile = new java.io.File("TextTemplateWithUserFields.odt");
163 StringBuffer sTemplateFileUrl = new StringBuffer("file:///");
164 sTemplateFileUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
166 XComponent xTemplateComponent =
167 newDocComponentFromTemplate( sTemplateFileUrl.toString() );
169 // get XTextFieldsSupplier, XBookmarksSupplier interfaces
170 XTextFieldsSupplier xTextFieldsSupplier = UnoRuntime.queryInterface(XTextFieldsSupplier.class,
171 xTemplateComponent);
172 XBookmarksSupplier xBookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, xTemplateComponent);
174 // access the TextFields and the TextFieldMasters collections
175 XNameAccess xNamedFieldMasters = xTextFieldsSupplier.getTextFieldMasters();
176 XEnumerationAccess xEnumeratedFields = xTextFieldsSupplier.getTextFields();
178 // iterate over hashtable and insert values into field masters
179 for(Iterator<String> iter = recipient.keySet().iterator(); iter.hasNext(); ) {
180 // get column name
181 String key = iter.next();
183 // access corresponding field master
184 Object fieldMaster = xNamedFieldMasters.getByName(
185 "com.sun.star.text.fieldmaster.User." + key);
187 // query the XPropertySet interface, we need to set the Content property
188 XPropertySet xPropertySet = UnoRuntime.queryInterface(
189 XPropertySet.class, fieldMaster);
191 // insert the column value into field master
192 xPropertySet.setPropertyValue("Content", recipient.get(key));
194 // afterwards we must refresh the textfields collection
195 XRefreshable xRefreshable = UnoRuntime.queryInterface(
196 XRefreshable.class, xEnumeratedFields);
197 xRefreshable.refresh();
199 // accessing the Bookmarks collection of the document
200 XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks();
202 // find the bookmark named "Subscription"
203 Object bookmark = xNamedBookmarks.getByName("Subscription");
204 // we need its XTextRange which is available from getAnchor(),
205 // so query for XTextContent
206 XTextContent xBookmarkContent = UnoRuntime.queryInterface(
207 XTextContent.class, bookmark);
208 // get the anchor of the bookmark (its XTextRange)
209 XTextRange xBookmarkRange = xBookmarkContent.getAnchor();
210 // set string at the bookmark position
211 xBookmarkRange.setString("subscription for the Manatee Journal");
215 /** Sample for document changes, starting at the current view cursor position
216 * The sample changes the paragraph style and the character style at the
217 * current view cursor selection Open the sample file ViewCursorExampleFile,
218 * select some text and run the example.
219 * The current paragraph will be set to Quotations paragraph style.
220 * The selected text will be set to Quotation character style.
222 private void viewCursorExample() throws java.lang.Exception {
223 // get the remote service manager
224 mxRemoteServiceManager = this.getRemoteServiceManager();
225 // get the Desktop service
226 Object desktop = mxRemoteServiceManager.createInstanceWithContext(
227 "com.sun.star.frame.Desktop", mxRemoteContext);
228 // query its XDesktop interface, we need the current component
229 XDesktop xDesktop = UnoRuntime.queryInterface(
230 XDesktop.class, desktop);
231 // retrieve the current component and access the controller
232 XComponent xCurrentComponent = xDesktop.getCurrentComponent();
233 XModel xModel = UnoRuntime.queryInterface(XModel.class,
234 xCurrentComponent);
235 XController xController = xModel.getCurrentController();
236 // the controller gives us the TextViewCursor
237 XTextViewCursorSupplier xViewCursorSupplier =
238 UnoRuntime.queryInterface(
239 XTextViewCursorSupplier.class, xController);
240 XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor();
242 // query its XPropertySet interface, we want to set character and paragraph
243 // properties
244 XPropertySet xCursorPropertySet = UnoRuntime.queryInterface(
245 XPropertySet.class, xViewCursor);
246 // set the appropriate properties for character and paragraph style
247 xCursorPropertySet.setPropertyValue("CharStyleName", "Quotation");
248 xCursorPropertySet.setPropertyValue("ParaStyleName", "Quotations");
249 // print the current page number
250 XPageCursor xPageCursor = UnoRuntime.queryInterface(
251 XPageCursor.class, xViewCursor);
252 System.out.println("The current page number is " + xPageCursor.getPage());
253 // the model cursor is much more powerful, so
254 // we create a model cursor at the current view cursor position with the
255 // following steps:
256 // get the Text service from the TextViewCursor, it is an XTextRange:
257 XText xDocumentText = xViewCursor.getText();
258 // create a model cursor from the viewcursor
259 XTextCursor xModelCursor = xDocumentText.createTextCursorByRange(
260 xViewCursor.getStart());
261 // now we could query XWordCursor, XSentenceCursor and XParagraphCursor
262 // or XDocumentInsertable, XSortable or XContentEnumerationAccess
263 // and work with the properties of com.sun.star.text.TextCursor
264 // in this case we just go to the end of the paragraph and add some text.
265 XParagraphCursor xParagraphCursor = UnoRuntime.queryInterface(XParagraphCursor.class, xModelCursor);
266 // goto the end of the paragraph
267 xParagraphCursor.gotoEndOfParagraph(false);
268 xParagraphCursor.setString(" ***** Fin de semana! ******");
272 /** Sample for the various editing facilities described in the
273 * developer's manual
275 private void editingExample () throws java.lang.Exception {
276 // create empty swriter document
277 XComponent xEmptyWriterComponent = newDocComponent("swriter");
278 // query its XTextDocument interface to get the text
279 mxDoc = UnoRuntime.queryInterface(
280 XTextDocument.class, xEmptyWriterComponent);
282 // get a reference to the body text of the document
283 mxDocText = mxDoc.getText();
285 // Get a reference to the document's property set. This contains document
286 // information like the current word count
287 UnoRuntime.queryInterface(XPropertySet.class, mxDoc );
289 // Simple text insertion example
290 BodyTextExample ();
291 // Example using text ranges to insert strings at the beginning or end
292 // of a text range
293 TextRangeExample ();
294 // Create a document cursor and remember it, it will be used in most
295 // of the following examples
296 mxDocCursor = mxDocText.createTextCursor();
297 // Demonstrate some of the different cursor types (word, sentence)
298 TextCursorExample ();
300 // Access the text document's multi service factory, which we will need
301 // for most of the following examples
302 mxDocFactory = UnoRuntime.queryInterface(
303 XMultiServiceFactory.class, mxDoc );
305 // Examples of text fields, dependent text fields and field masters
306 TextFieldExample ();
308 // Example of using an XEnumerationAccess to iterate over paragraphs and
309 // set properties of each paragraph as we do so
310 ParagraphExample ();
312 // Example of creating and manipulating a text frame
313 TextFrameExample ();
315 // Example of creating and manipulating a text table, text table rows
316 // and text table cells get a new random generator
317 maRandom = new Random();
318 TextTableExample ();
320 // Example of creating, inserting and manipulating text sections, as
321 // well as an example of how to refresh the document
322 TextSectionExample ();
324 // Example of creating a text section over a block of text and formatting
325 // the text section into columns, as well as how to insert an empty
326 // paragraph using the XRelativeTextContentInsert
327 TextColumnsExample ();
329 // Example of creating the NumberingRules service and adjusting
330 // NumberingTypes and NumberingLevels
331 NumberingExample ();
333 // Example of how to use the XStyleFamiliesSupplier interface of the
334 // document and how to create, insert and apply styles
335 StylesExample ();
336 IndexExample ();
338 // Example of how to create and manipulate reference marks and GetReference
339 // text fields
340 ReferenceExample ();
342 // Example of how to create and insert Footnotes and how to use the
343 // XFootnotesSupplier interface of the document
344 FootnoteExample ();
346 // This method demonstrates how to create shapes from the document factory
347 // and how to access the draw page of the document using the
348 // XDrawPageSupplier interface
349 DrawPageExample ();
351 mxFactory = UnoRuntime.queryInterface(
352 XMultiServiceFactory.class, mxRemoteServiceManager);
353 // This example demonstrates the use of the AutoTextContainer,
354 // AutoTextGroup and AutoTextEntry services and shows how to create,
355 // insert and modify auto text blocks
356 AutoTextExample ();
359 protected void storePrintExample() throws java.lang.Exception {
360 // get the remote service manager
361 mxRemoteServiceManager = this.getRemoteServiceManager();
362 // retrieve the Desktop object, we need its XComponentLoader
363 Object desktop = mxRemoteServiceManager.createInstanceWithContext(
364 "com.sun.star.frame.Desktop", mxRemoteContext);
365 XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop);
366 PropertyValue[] loadProps = new PropertyValue[0];
368 java.io.File sourceFile = new java.io.File("PrintDemo.odt");
369 StringBuffer sLoadFileUrl = new StringBuffer("file:///");
370 sLoadFileUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
372 XComponent xDoc = xComponentLoader.loadComponentFromURL(
373 sLoadFileUrl.toString(), "_blank", 0, loadProps);
375 if ( xDoc != null ) {
376 sourceFile = new java.io.File(sOutputDir);
377 StringBuffer sStoreFileUrl = new StringBuffer();
378 sStoreFileUrl.append(sourceFile.toURI().toURL().toString());
379 sStoreFileUrl.append("somepopularfileformat.doc");
381 storeDocComponent(xDoc, sStoreFileUrl.toString() );
382 printDocComponent(xDoc);
386 private XMultiComponentFactory getRemoteServiceManager()
387 throws java.lang.Exception
389 if (mxRemoteContext == null && mxRemoteServiceManager == null) {
390 // get the remote office context. If necessary a new office
391 // process is started
392 mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
393 System.out.println("Connected to a running office ...");
394 mxRemoteServiceManager = mxRemoteContext.getServiceManager();
396 return mxRemoteServiceManager;
399 protected XComponent newDocComponent(String docType)
400 throws java.lang.Exception
402 String loadUrl = "private:factory/" + docType;
403 mxRemoteServiceManager = this.getRemoteServiceManager();
404 Object desktop = mxRemoteServiceManager.createInstanceWithContext(
405 "com.sun.star.frame.Desktop", mxRemoteContext);
406 XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop);
407 PropertyValue[] loadProps = new PropertyValue[0];
408 return xComponentLoader.loadComponentFromURL(loadUrl, "_blank",
409 0, loadProps);
412 /** Load a document as template
414 protected XComponent newDocComponentFromTemplate(String loadUrl)
415 throws java.lang.Exception
417 // get the remote service manager
418 mxRemoteServiceManager = this.getRemoteServiceManager();
419 // retrieve the Desktop object, we need its XComponentLoader
420 Object desktop = mxRemoteServiceManager.createInstanceWithContext(
421 "com.sun.star.frame.Desktop", mxRemoteContext);
422 XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop);
424 // define load properties according to com.sun.star.document.MediaDescriptor
425 // the boolean property AsTemplate tells the office to create a new document
426 // from the given file
427 PropertyValue[] loadProps = new PropertyValue[1];
428 loadProps[0] = new PropertyValue();
429 loadProps[0].Name = "AsTemplate";
430 loadProps[0].Value = Boolean.TRUE;
431 // load
432 return xComponentLoader.loadComponentFromURL(loadUrl, "_blank",
433 0, loadProps);
436 /** Load a document with arguments (text purposes)
438 protected void storeDocComponent(XComponent xDoc, String storeUrl)
439 throws java.lang.Exception
442 XStorable xStorable = UnoRuntime.queryInterface(
443 XStorable.class, xDoc);
444 PropertyValue[] storeProps = new PropertyValue[1];
445 storeProps[0] = new PropertyValue();
446 storeProps[0].Name = "FilterName";
447 storeProps[0].Value = "MS Word 97";
449 System.out.println("... store \"PrintDemo.odt\" to \"" + storeUrl + "\".");
450 xStorable.storeAsURL(storeUrl, storeProps);
453 protected void printDocComponent(XComponent xDoc) throws java.lang.Exception {
454 XPrintable xPrintable = UnoRuntime.queryInterface(
455 XPrintable.class, xDoc);
456 PropertyValue[] printerDesc = new PropertyValue[1];
457 printerDesc[0] = new PropertyValue();
458 printerDesc[0].Name = "Name";
459 printerDesc[0].Value = aPrinterName;
461 xPrintable.setPrinter(printerDesc);
463 PropertyValue[] printOpts = new PropertyValue[1];
464 printOpts[0] = new PropertyValue();
465 printOpts[0].Name = "Pages";
466 printOpts[0].Value = "1";
468 xPrintable.print(printOpts);
471 // Setting the whole text of a document as one string
472 protected void BodyTextExample ()
474 // Body Text and TextDocument example
477 // demonstrate simple text insertion
478 mxDocText.setString ( "This is the new body text of the document."
479 + "\n\nThis is on the second line.\n\n" );
481 catch ( Exception e )
483 e.printStackTrace();
487 // Adding a string at the end or the beginning of text
488 protected void TextRangeExample ()
492 // Get a text range referring to the beginning of the text document
493 XTextRange xStart = mxDocText.getStart();
494 // use setString to insert text at the beginning
495 xStart.setString ( "This is text inserted at the beginning.\n\n" );
496 // Get a text range referring to the end of the text document
497 XTextRange xEnd = mxDocText.getEnd();
498 // use setString to insert text at the end
499 xEnd.setString ( "This is text inserted at the end.\n\n" );
501 catch ( Exception e )
503 e.printStackTrace();
507 /** moving a text cursor, selecting text and overwriting it
509 protected void TextCursorExample ()
513 // First, get the XSentenceCursor interface of our text cursor
514 XSentenceCursor xSentenceCursor = UnoRuntime.queryInterface(XSentenceCursor.class, mxDocCursor );
515 // Goto the next cursor, without selecting it
516 xSentenceCursor.gotoNextSentence( false );
517 // Get the XWordCursor interface of our text cursor
518 XWordCursor xWordCursor = UnoRuntime.queryInterface(
519 XWordCursor.class, mxDocCursor );
520 // Skip the first four words of this sentence and select the fifth
521 xWordCursor.gotoNextWord( false );
522 xWordCursor.gotoNextWord( false );
523 xWordCursor.gotoNextWord( false );
524 xWordCursor.gotoNextWord( false );
525 xWordCursor.gotoNextWord( true );
526 // Use the XSimpleText interface to insert a word at the current cursor
527 // location, over-writing the current selection (the fifth word
528 // selected above)
529 mxDocText.insertString ( xWordCursor, "old ", true );
531 // Access the property set of the cursor, and set the currently
532 // selected text (which is the string we just inserted) to be bold
533 XPropertySet xCursorProps = UnoRuntime.queryInterface(
534 XPropertySet.class, mxDocCursor );
535 xCursorProps.setPropertyValue ( "CharWeight",
536 new Float(com.sun.star.awt.FontWeight.BOLD) );
538 // replace the '.' at the end of the sentence with a new string
539 xSentenceCursor.gotoEndOfSentence( false );
540 xWordCursor.gotoPreviousWord( true );
541 mxDocText.insertString (xWordCursor,
542 ", which has been changed with text cursors!",
543 true);
545 catch ( Exception e )
547 e.printStackTrace();
551 /** This method inserts both a date field and a user field containing the
552 * number '42'
554 protected void TextFieldExample ()
558 // Use the text document's factory to create a DateTime text field,
559 // and access its XTextField interface
560 XTextField xDateField = UnoRuntime.queryInterface (
561 XTextField.class, mxDocFactory.createInstance (
562 "com.sun.star.text.TextField.DateTime" ) );
564 // Insert it at the end of the document
565 mxDocText.insertTextContent ( mxDocText.getEnd(), xDateField, false );
567 // Use the text document's factory to create a user text field,
568 // and access its XDependentTextField interface
569 XDependentTextField xUserField =
570 UnoRuntime.queryInterface (
571 XDependentTextField.class, mxDocFactory.createInstance (
572 "com.sun.star.text.TextField.User" ) );
574 // Create a fieldmaster for our newly created User Text field, and
575 // access its XPropertySet interface
576 XPropertySet xMasterPropSet = UnoRuntime.queryInterface(
577 XPropertySet.class, mxDocFactory.createInstance (
578 "com.sun.star.text.fieldmaster.User" ) );
580 // Set the name and value of the FieldMaster
581 xMasterPropSet.setPropertyValue ( "Name", "UserEmperor" );
582 xMasterPropSet.setPropertyValue ( "Value", Integer.valueOf( 42 ) );
584 // Attach the field master to the user field
585 xUserField.attachTextFieldMaster ( xMasterPropSet );
587 // Move the cursor to the end of the document
588 mxDocCursor.gotoEnd( false );
589 // insert a paragraph break using the XSimpleText interface
590 mxDocText.insertControlCharacter (
591 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
593 // Insert the user field at the end of the document
594 mxDocText.insertTextContent ( mxDocText.getEnd(), xUserField, false );
596 catch ( Exception e )
598 e.printStackTrace();
602 /** This method demonstrates how to iterate over paragraphs
604 protected void ParagraphExample ()
608 // The service 'com.sun.star.text.Text' supports the XEnumerationAccess
609 // interface to provide an enumeration of the paragraphs contained by
610 // the text the service refers to.
612 // Here, we access this interface
613 XEnumerationAccess xParaAccess = UnoRuntime.queryInterface(XEnumerationAccess.class, mxDocText );
614 // Call the XEnumerationAccess's only method to access the actual
615 // Enumeration
616 XEnumeration xParaEnum = xParaAccess.createEnumeration();
618 // While there are paragraphs, do things to them
619 while ( xParaEnum.hasMoreElements() )
621 // Get a reference to the next paragraphs XServiceInfo interface.
622 // TextTables are also part of this enumeration access, so we ask
623 // the element if it is a TextTable, if it doesn't support the
624 // com.sun.star.text.TextTable service, then it is safe to assume
625 // that it really is a paragraph
626 XServiceInfo xInfo = UnoRuntime.queryInterface(
627 XServiceInfo.class, xParaEnum.nextElement() );
628 if ( !xInfo.supportsService ( "com.sun.star.text.TextTable" ) )
630 // Access the paragraph's property set...the properties in this
631 // property set are listed in:
632 // com.sun.star.style.ParagraphProperties
633 XPropertySet xSet = UnoRuntime.queryInterface(
634 XPropertySet.class, xInfo );
635 // Set the justification to be center justified
636 xSet.setPropertyValue ( "ParaAdjust",
637 com.sun.star.style.ParagraphAdjust.CENTER );
641 catch ( Exception e )
643 e.printStackTrace();
647 /** This method returns a random double which isn't too high or too low
649 protected double getRandomDouble ()
651 return ( ( maRandom.nextInt() % 1000 ) * maRandom.nextDouble () );
654 /** This method sets the text colour of the cell referred to by sCellName to
655 white and inserts the string sText in it
657 protected static void insertIntoCell(String sCellName, String sText,
658 XTextTable xTable)
660 // Access the XText interface of the cell referred to by sCellName
661 XText xCellText = UnoRuntime.queryInterface(
662 XText.class, xTable.getCellByName ( sCellName ) );
664 // create a text cursor from the cells XText interface
665 XTextCursor xCellCursor = xCellText.createTextCursor();
666 // Get the property set of the cell's TextCursor
667 XPropertySet xCellCursorProps = UnoRuntime.queryInterface(
668 XPropertySet.class, xCellCursor );
672 // Set the colour of the text to white
673 xCellCursorProps.setPropertyValue( "CharColor", Integer.valueOf(16777215));
675 catch ( Exception e)
677 e.printStackTrace();
679 // Set the text in the cell to sText
680 xCellText.setString( sText );
683 /** This method shows how to create and insert a text table, as well as insert
684 text and formulae into the cells of the table
686 protected void TextTableExample ()
690 // Create a new table from the document's factory
691 XTextTable xTable = UnoRuntime.queryInterface(
692 XTextTable.class, mxDocFactory .createInstance(
693 "com.sun.star.text.TextTable" ) );
695 // Specify that we want the table to have 4 rows and 4 columns
696 xTable.initialize( 4, 4 );
698 // Insert the table into the document
699 mxDocText.insertTextContent( mxDocCursor, xTable, false);
700 // Get an XIndexAccess of the table rows
701 XIndexAccess xRows = xTable.getRows();
703 // Access the property set of the first row (properties listed in
704 // service description: com.sun.star.text.TextTableRow)
705 XPropertySet xRow = UnoRuntime.queryInterface(
706 XPropertySet.class, xRows.getByIndex ( 0 ) );
707 // If BackTransparent is false, then the background color is visible
708 xRow.setPropertyValue( "BackTransparent", Boolean.FALSE);
709 // Specify the color of the background to be dark blue
710 xRow.setPropertyValue( "BackColor", Integer.valueOf(6710932));
712 // Access the property set of the whole table
713 XPropertySet xTableProps = UnoRuntime.queryInterface(
714 XPropertySet.class, xTable );
715 // We want visible background colors
716 xTableProps.setPropertyValue( "BackTransparent", Boolean.FALSE);
717 // Set the background colour to light blue
718 xTableProps.setPropertyValue( "BackColor", Integer.valueOf(13421823));
720 // set the text (and text colour) of all the cells in the first row
721 // of the table
722 insertIntoCell( "A1", "First Column", xTable );
723 insertIntoCell( "B1", "Second Column", xTable );
724 insertIntoCell( "C1", "Third Column", xTable );
725 insertIntoCell( "D1", "Results", xTable );
727 // Insert random numbers into the first this three cells of each
728 // remaining row
729 xTable.getCellByName( "A2" ).setValue( getRandomDouble() );
730 xTable.getCellByName( "B2" ).setValue( getRandomDouble() );
731 xTable.getCellByName( "C2" ).setValue( getRandomDouble() );
733 xTable.getCellByName( "A3" ).setValue( getRandomDouble() );
734 xTable.getCellByName( "B3" ).setValue( getRandomDouble() );
735 xTable.getCellByName( "C3" ).setValue( getRandomDouble() );
737 xTable.getCellByName( "A4" ).setValue( getRandomDouble() );
738 xTable.getCellByName( "B4" ).setValue( getRandomDouble() );
739 xTable.getCellByName( "C4" ).setValue( getRandomDouble() );
741 // Set the last cell in each row to be a formula that calculates
742 // the sum of the first three cells
743 xTable.getCellByName( "D2" ).setFormula( "sum <A2:C2>" );
744 xTable.getCellByName( "D3" ).setFormula( "sum <A3:C3>" );
745 xTable.getCellByName( "D4" ).setFormula( "sum <A4:C4>" );
747 catch (Exception e)
749 e.printStackTrace();
752 /** This method shows how to create and manipulate text frames
754 protected void TextFrameExample ()
758 // Use the document's factory to create a new text frame and
759 // immediately access its XTextFrame interface
760 XTextFrame xFrame = UnoRuntime.queryInterface (
761 XTextFrame.class, mxDocFactory.createInstance (
762 "com.sun.star.text.TextFrame" ) );
764 // Access the XShape interface of the TextFrame
765 XShape xShape = UnoRuntime.queryInterface(XShape.class, xFrame);
766 // Access the XPropertySet interface of the TextFrame
767 XPropertySet xFrameProps = UnoRuntime.queryInterface(
768 XPropertySet.class, xFrame );
770 // Set the size of the new Text Frame using the XShape's 'setSize'
771 // method
772 Size aSize = new Size();
773 aSize.Height = 400;
774 aSize.Width = 15000;
775 xShape.setSize(aSize);
776 // Set the AnchorType to
777 // com.sun.star.text.TextContentAnchorType.AS_CHARACTER
778 xFrameProps.setPropertyValue( "AnchorType",
779 TextContentAnchorType.AS_CHARACTER );
780 // Go to the end of the text document
781 mxDocCursor.gotoEnd( false );
782 // Insert a new paragraph
783 mxDocText.insertControlCharacter (
784 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
785 // Then insert the new frame
786 mxDocText.insertTextContent(mxDocCursor, xFrame, false);
788 // Access the XText interface of the text contained within the frame
789 XText xFrameText = xFrame.getText();
790 // Create a TextCursor over the frame's contents
791 XTextCursor xFrameCursor = xFrameText.createTextCursor();
792 // Insert some text into the frame
793 xFrameText.insertString(
794 xFrameCursor, "The first line in the newly created text frame.",
795 false );
796 xFrameText.insertString(
797 xFrameCursor, "\nThe second line in the new text frame.", false );
798 // Insert a paragraph break into the document (not the frame)
799 mxDocText.insertControlCharacter (
800 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
802 catch (Exception e)
804 e.printStackTrace();
808 /** This example demonstrates the use of the AutoTextContainer, AutoTextGroup
809 and AutoTextEntry services and shows how to create, insert and modify
810 auto text blocks
812 protected void AutoTextExample ()
816 // Go to the end of the document
817 mxDocCursor.gotoEnd( false );
818 // Insert two paragraphs
819 mxDocText.insertControlCharacter ( mxDocCursor,
820 ControlCharacter.PARAGRAPH_BREAK, false );
821 mxDocText.insertControlCharacter ( mxDocCursor,
822 ControlCharacter.PARAGRAPH_BREAK, false );
823 // Position the cursor in the second paragraph
824 XParagraphCursor xParaCursor = UnoRuntime.queryInterface(XParagraphCursor.class, mxDocCursor );
825 xParaCursor.gotoPreviousParagraph ( false );
827 // Get an XNameAccess interface to all auto text groups from the
828 // document factory
829 XNameAccess xContainer = UnoRuntime.queryInterface(
830 XNameAccess.class, mxFactory.createInstance (
831 "com.sun.star.text.AutoTextContainer" ) );
833 // Create a new table at the document factory
834 XTextTable xTable = UnoRuntime.queryInterface(
835 XTextTable.class, mxDocFactory .createInstance(
836 "com.sun.star.text.TextTable" ) );
838 // Store the names of all auto text groups in an array of strings
839 String[] aGroupNames = xContainer.getElementNames();
841 // Make sure we have at least one group name
842 if ( aGroupNames.length > 0 )
844 // initialise the table to have a row for every autotext group
845 // in a single column + one additional row for a header
846 xTable.initialize( aGroupNames.length+1,1);
848 // Access the XPropertySet of the table
849 XPropertySet xTableProps = UnoRuntime.queryInterface(
850 XPropertySet.class, xTable );
852 // We want a visible background
853 xTableProps.setPropertyValue( "BackTransparent",
854 Boolean.FALSE);
856 // We want the background to be light blue
857 xTableProps.setPropertyValue( "BackColor", Integer.valueOf(13421823));
859 // Inser the table into the document
860 mxDocText.insertTextContent( mxDocCursor, xTable, false);
862 // Get an XIndexAccess to all table rows
863 XIndexAccess xRows = xTable.getRows();
865 // Get the first row in the table
866 XPropertySet xRow = UnoRuntime.queryInterface(
867 XPropertySet.class, xRows.getByIndex ( 0 ) );
869 // We want the background of the first row to be visible too
870 xRow.setPropertyValue( "BackTransparent", Boolean.FALSE);
872 // And let's make it dark blue
873 xRow.setPropertyValue( "BackColor", Integer.valueOf(6710932));
875 // Put a description of the table contents into the first cell
876 insertIntoCell( "A1", "AutoText Groups", xTable);
878 // Create a table cursor pointing at the second cell in the first
879 // column
880 XTextTableCursor xTableCursor = xTable.createCursorByCellName("A2");
882 // Loop over the group names
883 for ( int i = 0 ; i < aGroupNames.length ; i ++ )
885 // Get the name of the current cell
886 String sCellName = xTableCursor.getRangeName ();
888 // Get the XText interface of the current cell
889 XText xCellText = UnoRuntime.queryInterface (
890 XText.class, xTable.getCellByName ( sCellName ) );
892 // Set the cell contents of the current cell to be
893 //the name of the of an autotext group
894 xCellText.setString ( aGroupNames[i] );
896 // Access the autotext group with this name
897 XAutoTextGroup xGroup = UnoRuntime.queryInterface (XAutoTextGroup.class,
898 xContainer.getByName(aGroupNames[i]));
900 // Get the titles of each autotext block in this group
901 String [] aBlockNames = xGroup.getTitles();
903 // Make sure that the autotext group contains at least one block
904 if ( aBlockNames.length > 0 )
906 // Split the current cell vertically into two separate cells
907 xTableCursor.splitRange ( (short) 1, false );
909 // Put the cursor in the newly created right hand cell
910 // and select it
911 xTableCursor.goRight ( (short) 1, false );
913 // Split this cell horizontally to make a separate cell
914 // for each Autotext block
915 if ( ( aBlockNames.length -1 ) > 0 )
916 xTableCursor.splitRange (
917 (short) (aBlockNames.length - 1), true );
919 // loop over the block names
920 for ( int j = 0 ; j < aBlockNames.length ; j ++ )
922 // Get the XText interface of the current cell
923 xCellText = UnoRuntime.queryInterface (
924 XText.class, xTable.getCellByName (
925 xTableCursor.getRangeName() ) );
927 // Set the text contents of the current cell to the
928 // title of an Autotext block
929 xCellText.setString ( aBlockNames[j] );
931 // Move the cursor down one cell
932 xTableCursor.goDown( (short)1, false);
935 // Go back to the cell we originally split
936 xTableCursor.gotoCellByName ( sCellName, false );
938 // Go down one cell
939 xTableCursor.goDown( (short)1, false);
942 XAutoTextGroup xGroup;
943 String [] aBlockNames;
945 // Add a depth so that we only generate 200 numbers before giving up
946 // on finding a random autotext group that contains autotext blocks
947 int nDepth = 0;
950 // Generate a random, positive number which is lower than
951 // the number of autotext groups
952 int nRandom = Math.abs ( maRandom.nextInt() %
953 aGroupNames.length );
955 // Get the autotext group at this name
956 xGroup = UnoRuntime.queryInterface (
957 XAutoTextGroup.class, xContainer.getByName (
958 aGroupNames[ nRandom ] ) );
960 // Fill our string array with the names of all the blocks in
961 // this group
962 aBlockNames = xGroup.getElementNames();
964 // increment our depth counter
965 ++nDepth;
967 while ( nDepth < 200 && aBlockNames.length == 0 );
968 // If we managed to find a group containing blocks...
969 if ( aBlockNames.length > 0 )
971 // Pick a random block in this group and get its
972 // XAutoTextEntry interface
973 int nRandom = Math.abs ( maRandom.nextInt()
974 % aBlockNames.length );
975 XAutoTextEntry xEntry = UnoRuntime.queryInterface (
976 XAutoTextEntry.class, xGroup.getByName (
977 aBlockNames[ nRandom ] ) );
978 // insert the modified autotext block at the end of the document
979 xEntry.applyTo ( mxDocCursor );
981 // Get the titles of all text blocks in this AutoText group
982 String [] aBlockTitles = xGroup.getTitles();
984 // Get the XNamed interface of the autotext group
985 XNamed xGroupNamed = UnoRuntime.queryInterface (
986 XNamed.class, xGroup );
988 // Output the short cut and title of the random block
989 //and the name of the group it's from
990 System.out.println ( "Inserted the Autotext '" +
991 aBlockTitles[nRandom]
992 + "', shortcut '" + aBlockNames[nRandom]
993 + "' from group '"
994 + xGroupNamed.getName());
998 // Go to the end of the document
999 mxDocCursor.gotoEnd( false );
1000 // Insert new paragraph
1001 mxDocText.insertControlCharacter (
1002 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1004 // Position cursor in new paragraph
1005 xParaCursor.gotoPreviousParagraph ( false );
1007 // Insert a string in the new paragraph
1008 mxDocText.insertString ( mxDocCursor,
1009 "Some text for a new autotext block", false );
1011 // Go to the end of the document
1012 mxDocCursor.gotoEnd( false );
1014 catch (Exception e)
1016 e.printStackTrace();
1020 /** This method demonstrates how to insert indexes and index marks
1022 protected void IndexExample ()
1026 // Go to the end of the document
1027 mxDocCursor.gotoEnd( false );
1028 // Insert a new paragraph and position the cursor in it
1029 mxDocText.insertControlCharacter ( mxDocCursor,
1030 ControlCharacter.PARAGRAPH_BREAK, false );
1031 XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1032 xParaCursor.gotoPreviousParagraph ( false );
1034 // Create a new ContentIndexMark and get its XPropertySet interface
1035 XPropertySet xEntry = UnoRuntime.queryInterface(
1036 XPropertySet.class,
1037 mxDocFactory.createInstance("com.sun.star.text.ContentIndexMark"));
1039 // Set the text to be displayed in the index
1040 xEntry.setPropertyValue(
1041 "AlternativeText", "Big dogs! Falling on my head!");
1043 // The Level property _must_ be set
1044 xEntry.setPropertyValue ( "Level", Short.valueOf( (short) 1 ) );
1046 // Create a ContentIndex and access its XPropertySet interface
1047 XPropertySet xIndex = UnoRuntime.queryInterface(
1048 XPropertySet.class,
1049 mxDocFactory.createInstance ( "com.sun.star.text.ContentIndex" ) );
1051 // Again, the Level property _must_ be set
1052 xIndex.setPropertyValue ( "Level", Short.valueOf( (short) 10 ) );
1054 // Access the XTextContent interfaces of both the Index and the
1055 // IndexMark
1056 XTextContent xIndexContent = UnoRuntime.queryInterface(
1057 XTextContent.class, xIndex );
1058 XTextContent xEntryContent = UnoRuntime.queryInterface(
1059 XTextContent.class, xEntry );
1061 // Insert both in the document
1062 mxDocText.insertTextContent ( mxDocCursor, xEntryContent, false );
1063 mxDocText.insertTextContent ( mxDocCursor, xIndexContent, false );
1065 // Get the XDocumentIndex interface of the Index
1066 XDocumentIndex xDocIndex = UnoRuntime.queryInterface(
1067 XDocumentIndex.class, xIndex );
1069 // And call its update method
1070 xDocIndex.update();
1072 catch (Exception e)
1074 e.printStackTrace();
1078 /** This method demonstrates how to create and insert reference marks, and
1079 * GetReference Text Fields
1081 protected void ReferenceExample ()
1085 // Go to the end of the document
1086 mxDocCursor.gotoEnd( false );
1088 // Insert a paragraph break
1089 mxDocText.insertControlCharacter (
1090 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1092 // Get the Paragraph cursor
1093 XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1095 // Move the cursor into the new paragraph
1096 xParaCursor.gotoPreviousParagraph ( false );
1098 // Create a new ReferenceMark and get its XNamed interface
1099 XNamed xRefMark = UnoRuntime.queryInterface(XNamed.class,
1100 mxDocFactory.createInstance ("com.sun.star.text.ReferenceMark"));
1102 // Set the name to TableHeader
1103 xRefMark.setName ( "TableHeader" );
1105 // Get the TextTablesSupplier interface of the document
1106 XTextTablesSupplier xTableSupplier = UnoRuntime.queryInterface(XTextTablesSupplier.class, mxDoc);
1108 // Get an XIndexAccess of TextTables
1109 XIndexAccess xTables = UnoRuntime.queryInterface(
1110 XIndexAccess.class, xTableSupplier.getTextTables());
1112 // We've only inserted one table, so get the first one from index zero
1113 XTextTable xTable = UnoRuntime.queryInterface (
1114 XTextTable.class, xTables.getByIndex( 0 ) );
1116 // Get the first cell from the table
1117 XText xTableText = UnoRuntime.queryInterface(
1118 XText.class, xTable.getCellByName ( "A1" ) );
1120 // Get a text cursor for the first cell
1121 XTextCursor xTableCursor = xTableText.createTextCursor();
1123 // Get the XTextContent interface of the reference mark so we can
1124 // insert it
1125 XTextContent xContent = UnoRuntime.queryInterface (
1126 XTextContent.class, xRefMark );
1128 // Insert the reference mark into the first cell of the table
1129 xTableText.insertTextContent ( xTableCursor, xContent, false );
1131 // Create a 'GetReference' text field to refer to the reference mark
1132 // we just inserted, and get its XPropertySet interface
1133 XPropertySet xFieldProps = UnoRuntime.queryInterface(
1134 XPropertySet.class, mxDocFactory.createInstance (
1135 "com.sun.star.text.TextField.GetReference" ) );
1137 // Get the XReferenceMarksSupplier interface of the document
1138 XReferenceMarksSupplier xRefSupplier = UnoRuntime.queryInterface( XReferenceMarksSupplier.class, mxDoc );
1140 // Get an XNameAccess which refers to all inserted reference marks
1141 XNameAccess xMarks = UnoRuntime.queryInterface (
1142 XNameAccess.class, xRefSupplier.getReferenceMarks() );
1144 // Put the names of each reference mark into an array of strings
1145 String[] aNames = xMarks.getElementNames();
1147 // Make sure that at least 1 reference mark actually exists
1148 // (well, we just inserted one!)
1149 if ( aNames.length > 0 )
1151 // Output the name of the first reference mark ('TableHeader')
1152 System.out.println (
1153 "GetReference text field inserted for ReferenceMark : "
1154 + aNames[0] );
1156 // Set the SourceName of the GetReference text field to
1157 // 'TableHeader'
1158 xFieldProps.setPropertyValue ( "SourceName", aNames[0] );
1160 // specify that the source is a reference mark (could also be a
1161 // footnote, bookmark or sequence field )
1162 xFieldProps.setPropertyValue ( "ReferenceFieldSource",
1163 Short.valueOf(ReferenceFieldSource.REFERENCE_MARK));
1165 // We want the reference displayed as 'above' or 'below'
1166 xFieldProps.setPropertyValue ( "ReferenceFieldPart",
1167 Short.valueOf(ReferenceFieldPart.UP_DOWN));
1170 // Get the XTextContent interface of the GetReference text field
1171 XTextContent xRefContent = UnoRuntime.queryInterface(
1172 XTextContent.class, xFieldProps );
1174 // Go to the end of the document
1175 mxDocCursor.gotoEnd( false );
1177 // Make some text to precede the reference
1178 mxDocText.insertString(mxDocText.getEnd(), "The table ", false);
1180 // Insert the text field
1181 mxDocText.insertTextContent(mxDocText.getEnd(), xRefContent, false);
1183 // And some text after the reference...
1184 mxDocText.insertString(mxDocText.getEnd(),
1185 " contains the sum of some random numbers.", false );
1187 // Refresh the document
1188 XRefreshable xRefresh = UnoRuntime.queryInterface(
1189 XRefreshable.class, mxDoc );
1190 xRefresh.refresh();
1193 catch (Exception e)
1195 e.printStackTrace();
1199 /** This method demonstrates how to create and insert footnotes, and how to
1200 access the XFootnotesSupplier interface of the document
1202 protected void FootnoteExample ()
1206 // Create a new footnote from the document factory and get its
1207 // XFootnote interface
1208 XFootnote xFootnote = UnoRuntime.queryInterface(
1209 XFootnote.class, mxDocFactory.createInstance (
1210 "com.sun.star.text.Footnote" ) );
1212 // Set the label to 'Numbers'
1213 xFootnote.setLabel ( "Numbers" );
1215 // Get the footnotes XTextContent interface so we can...
1216 XTextContent xContent = UnoRuntime.queryInterface (
1217 XTextContent.class, xFootnote );
1219 // ...insert it into the document
1220 mxDocText.insertTextContent ( mxDocCursor, xContent, false );
1222 // Get the XFootnotesSupplier interface of the document
1223 XFootnotesSupplier xFootnoteSupplier = UnoRuntime.queryInterface(XFootnotesSupplier.class, mxDoc );
1225 // Get an XIndexAccess interface to all footnotes
1226 XIndexAccess xFootnotes = UnoRuntime.queryInterface (
1227 XIndexAccess.class, xFootnoteSupplier.getFootnotes() );
1229 // Get the XFootnote interface to the first footnote inserted ('Numbers')
1230 XFootnote xNumbers = UnoRuntime.queryInterface (
1231 XFootnote.class, xFootnotes.getByIndex( 0 ) );
1233 // Get the XSimpleText interface to the Footnote
1234 XSimpleText xSimple = UnoRuntime.queryInterface (
1235 XSimpleText.class, xNumbers );
1237 // Create a text cursor for the foot note text
1238 XTextRange xRange = UnoRuntime.queryInterface (
1239 XTextRange.class, xSimple.createTextCursor() );
1241 // And insert the actual text of the footnote.
1242 xSimple.insertString (
1243 xRange, " The numbers were generated by using java.util.Random", false );
1245 catch (Exception e)
1247 e.printStackTrace();
1251 /** This method demonstrates how to create and manipulate shapes, and how to
1252 access the draw page of the document to insert shapes
1254 protected void DrawPageExample ()
1258 // Go to the end of the document
1259 mxDocCursor.gotoEnd( false );
1260 // Insert two new paragraphs
1261 mxDocText.insertControlCharacter(mxDocCursor,
1262 ControlCharacter.PARAGRAPH_BREAK, false);
1263 mxDocText.insertControlCharacter(mxDocCursor,
1264 ControlCharacter.PARAGRAPH_BREAK, false);
1266 // Get the XParagraphCursor interface of our document cursor
1267 XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1269 // Position the cursor in the 2nd paragraph
1270 xParaCursor.gotoPreviousParagraph ( false );
1272 // Create a RectangleShape using the document factory
1273 XShape xRect = UnoRuntime.queryInterface(
1274 XShape.class, mxDocFactory.createInstance (
1275 "com.sun.star.drawing.RectangleShape" ) );
1277 // Create an EllipseShape using the document factory
1278 XShape xEllipse = UnoRuntime.queryInterface(
1279 XShape.class, mxDocFactory.createInstance (
1280 "com.sun.star.drawing.EllipseShape" ) );
1282 // Set the size of both the ellipse and the rectangle
1283 Size aSize = new Size();
1284 aSize.Height = 4000;
1285 aSize.Width = 10000;
1286 xRect.setSize(aSize);
1287 aSize.Height = 3000;
1288 aSize.Width = 6000;
1289 xEllipse.setSize ( aSize );
1291 // Set the position of the Rectangle to the right of the ellipse
1292 Point aPoint = new Point();
1293 aPoint.X = 6100;
1294 aPoint.Y = 0;
1295 xRect.setPosition ( aPoint );
1297 // Get the XPropertySet interfaces of both shapes
1298 XPropertySet xRectProps = UnoRuntime.queryInterface(
1299 XPropertySet.class, xRect );
1300 XPropertySet xEllipseProps = UnoRuntime.queryInterface(
1301 XPropertySet.class, xEllipse );
1303 // And set the AnchorTypes of both shapes to 'AT_PARAGRAPH'
1304 xRectProps.setPropertyValue ( "AnchorType",
1305 TextContentAnchorType.AT_PARAGRAPH );
1306 xEllipseProps.setPropertyValue ( "AnchorType",
1307 TextContentAnchorType.AT_PARAGRAPH );
1309 // Access the XDrawPageSupplier interface of the document
1310 XDrawPageSupplier xDrawPageSupplier = UnoRuntime.queryInterface (XDrawPageSupplier.class, mxDoc );
1312 // Get the XShapes interface of the draw page
1313 XShapes xShapes = UnoRuntime.queryInterface (
1314 XShapes.class, xDrawPageSupplier.getDrawPage () );
1316 // Add both shapes
1317 xShapes.add ( xEllipse );
1318 xShapes.add ( xRect );
1321 This doesn't work, I am assured that FME and AMA are fixing it.
1323 XShapes xGrouper = (XShapes) UnoRuntime.queryInterface(
1324 XShapes.class, mxDocFactory.createInstance (
1325 "com.sun.star.drawing.GroupShape" ) );
1327 XShape xGrouperShape = (XShape) UnoRuntime.queryInterface(
1328 XShape.class, xGrouper );
1329 xShapes.add ( xGrouperShape );
1331 xGrouper.add ( xRect );
1332 xGrouper.add ( xEllipse );
1334 XShapeGrouper xShapeGrouper = (XShapeGrouper)
1335 UnoRuntime.queryInterface(XShapeGrouper.class, xShapes);
1336 xShapeGrouper.group ( xGrouper );
1340 catch (Exception e)
1342 e.printStackTrace();
1346 /** This method demonstrates how to create, insert and apply styles
1348 protected void StylesExample ()
1352 // Go to the end of the document
1353 mxDocCursor.gotoEnd( false );
1355 // Insert two paragraph breaks
1356 mxDocText.insertControlCharacter (
1357 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1358 mxDocText.insertControlCharacter (
1359 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1361 // Create a new style from the document's factory
1362 XStyle xStyle = UnoRuntime.queryInterface(
1363 XStyle.class, mxDocFactory.createInstance(
1364 "com.sun.star.style.ParagraphStyle" ) );
1366 // Access the XPropertySet interface of the new style
1367 XPropertySet xStyleProps = UnoRuntime.queryInterface(
1368 XPropertySet.class, xStyle );
1370 // Give the new style a light blue background
1371 xStyleProps.setPropertyValue ( "ParaBackColor", Integer.valueOf(13421823));
1373 // Get the StyleFamiliesSupplier interface of the document
1374 XStyleFamiliesSupplier xSupplier = UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, mxDoc);
1376 // Use the StyleFamiliesSupplier interface to get the XNameAccess
1377 // interface of the actual style families
1378 XNameAccess xFamilies = UnoRuntime.queryInterface (
1379 XNameAccess.class, xSupplier.getStyleFamilies() );
1381 // Access the 'ParagraphStyles' Family
1382 XNameContainer xFamily = UnoRuntime.queryInterface (
1383 XNameContainer.class,
1384 xFamilies.getByName ( "ParagraphStyles" ) );
1386 // Insert the newly created style into the ParagraphStyles family
1387 xFamily.insertByName ( "All-Singing All-Dancing Style", xStyle );
1389 // Get the XParagraphCursor interface of the document cursor
1390 XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1392 // Select the first paragraph inserted
1393 xParaCursor.gotoPreviousParagraph ( false );
1394 xParaCursor.gotoPreviousParagraph ( true );
1396 // Access the property set of the cursor selection
1397 XPropertySet xCursorProps = UnoRuntime.queryInterface(
1398 XPropertySet.class, mxDocCursor );
1400 // Set the style of the cursor selection to our newly created style
1401 xCursorProps.setPropertyValue ( "ParaStyleName",
1402 "All-Singing All-Dancing Style" );
1404 // Go back to the end
1405 mxDocCursor.gotoEnd ( false );
1407 // Select the last paragraph in the document
1408 xParaCursor.gotoNextParagraph ( true );
1410 // And reset its style to 'Standard' (the programmatic name for
1411 // the default style)
1412 xCursorProps.setPropertyValue ( "ParaStyleName", "Standard" );
1414 catch (Exception e)
1416 e.printStackTrace();
1420 /** This method demonstrates how to set numbering types and numbering levels
1421 using the com.sun.star.text.NumberingRules service
1423 protected void NumberingExample ()
1427 // Go to the end of the document
1428 mxDocCursor.gotoEnd( false );
1429 // Get the RelativeTextContentInsert interface of the document
1430 XRelativeTextContentInsert xRelative =
1431 UnoRuntime.queryInterface (
1432 XRelativeTextContentInsert.class, mxDocText );
1434 // Use the document's factory to create the NumberingRules service,
1435 // and get its XIndexAccess interface
1436 XIndexAccess xNum = UnoRuntime.queryInterface(
1437 XIndexAccess.class,
1438 mxDocFactory.createInstance( "com.sun.star.text.NumberingRules" ) );
1440 // Also get the NumberingRule's XIndexReplace interface
1441 XIndexReplace xReplace = UnoRuntime.queryInterface(
1442 XIndexReplace.class, xNum );
1444 // Create an array of XPropertySets, one for each of the three
1445 // paragraphs we're about to create
1446 XPropertySet xParas[] = new XPropertySet [ 3 ];
1447 for ( int i = 0 ; i < 3 ; ++ i )
1449 // Create a new paragraph
1450 XTextContent xNewPara = UnoRuntime.queryInterface(
1451 XTextContent.class, mxDocFactory.createInstance(
1452 "com.sun.star.text.Paragraph" ) );
1454 // Get the XPropertySet interface of the new paragraph and put
1455 // it in our array
1456 xParas[i] = UnoRuntime.queryInterface(
1457 XPropertySet.class, xNewPara );
1459 // Insert the new paragraph into the document after the fish
1460 // section. As it is an insert relative to the fish section, the
1461 // first paragraph inserted will be below the next two
1462 xRelative.insertTextContentAfter ( xNewPara, mxFishSection );
1464 // Separate from the above, but also needs to be done three times
1466 // Get the PropertyValue sequence for this numbering level
1467 PropertyValue [] aProps = (PropertyValue [] ) xNum.getByIndex ( i );
1469 // Iterate over the PropertyValue's for this numbering level,
1470 // looking for the 'NumberingType' property
1471 for ( int j = 0 ; j < aProps.length ; ++j )
1473 if ( aProps[j].Name.equals ( "NumberingType" ) )
1475 // Once we find it, set its value to a new type,
1476 // dependent on which numbering level we're currently on
1477 switch ( i )
1479 case 0 : aProps[j].Value =
1480 Short.valueOf(NumberingType.ROMAN_UPPER);
1481 break;
1482 case 1 : aProps[j].Value =
1483 Short.valueOf(NumberingType.CHARS_UPPER_LETTER);
1484 break;
1485 case 2 : aProps[j].Value =
1486 Short.valueOf(NumberingType.ARABIC);
1487 break;
1489 // Put the updated PropertyValue sequence back into the
1490 // NumberingRules service
1491 xReplace.replaceByIndex ( i, aProps );
1492 break;
1496 // Get the XParagraphCursor interface of our text cursor
1497 XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1498 // Go to the end of the document, then select the preceding paragraphs
1499 mxDocCursor.gotoEnd ( false );
1500 xParaCursor.gotoPreviousParagraph ( false );
1501 xParaCursor.gotoPreviousParagraph ( true );
1502 xParaCursor.gotoPreviousParagraph ( true );
1504 // Get the XPropertySet of the cursor's currently selected text
1505 XPropertySet xCursorProps = UnoRuntime.queryInterface(
1506 XPropertySet.class, mxDocCursor );
1508 // Set the updated Numbering rules to the cursor's property set
1509 xCursorProps.setPropertyValue ( "NumberingRules", xNum );
1510 mxDocCursor.gotoEnd( false );
1512 // Set the first paragraph that was inserted to a numbering level of
1513 // 2 (thus it will have Arabic style numbering)
1514 xParas[0].setPropertyValue ( "NumberingLevel", Short.valueOf((short) 2));
1516 // Set the second paragraph that was inserted to a numbering level of
1517 // 1 (thus it will have 'Chars Upper Letter' style numbering)
1518 xParas[1].setPropertyValue ( "NumberingLevel", Short.valueOf((short) 1));
1520 // Set the third paragraph that was inserted to a numbering level of
1521 // 0 (thus it will have 'Chars Upper Letter' style numbering)
1522 xParas[2].setPropertyValue ( "NumberingLevel", Short.valueOf((short) 0));
1524 catch (Exception e)
1526 e.printStackTrace();
1530 /** This method demonstrates how to create linked and unlinked sections
1532 protected void TextSectionExample ()
1536 // Go to the end of the document
1537 mxDocCursor.gotoEnd( false );
1538 // Insert two paragraph breaks
1539 mxDocText.insertControlCharacter (
1540 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1541 mxDocText.insertControlCharacter (
1542 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, true );
1544 // Create a new TextSection from the document factory and access
1545 // its XNamed interface
1546 XNamed xChildNamed = UnoRuntime.queryInterface(
1547 XNamed.class, mxDocFactory.createInstance(
1548 "com.sun.star.text.TextSection" ) );
1549 // Set the new sections name to 'Child_Section'
1550 xChildNamed.setName ( "Child_Section" );
1552 // Access the Child_Section's XTextContent interface and insert it
1553 // into the document
1554 XTextContent xChildSection = UnoRuntime.queryInterface(
1555 XTextContent.class, xChildNamed );
1556 mxDocText.insertTextContent ( mxDocCursor, xChildSection, false );
1558 // Access the XParagraphCursor interface of our text cursor
1559 XParagraphCursor xParaCursor = UnoRuntime.queryInterface(XParagraphCursor.class, mxDocCursor);
1561 // Go back one paragraph (into Child_Section)
1562 xParaCursor.gotoPreviousParagraph ( false );
1564 // Insert a string into the Child_Section
1565 mxDocText.insertString ( mxDocCursor, "This is a test", false );
1567 // Go to the end of the document
1568 mxDocCursor.gotoEnd( false );
1570 // Go back two paragraphs
1571 xParaCursor.gotoPreviousParagraph ( false );
1572 xParaCursor.gotoPreviousParagraph ( false );
1573 // Go to the end of the document, selecting the two paragraphs
1574 mxDocCursor.gotoEnd ( true );
1576 // Create another text section and access its XNamed interface
1577 XNamed xParentNamed = UnoRuntime.queryInterface(XNamed.class,
1578 mxDocFactory.createInstance("com.sun.star.text.TextSection"));
1580 // Set this text section's name to Parent_Section
1581 xParentNamed.setName ( "Parent_Section" );
1583 // Access the Parent_Section's XTextContent interface ...
1584 XTextContent xParentSection = UnoRuntime.queryInterface(
1585 XTextContent.class, xParentNamed );
1586 // ...and insert it into the document
1587 mxDocText.insertTextContent ( mxDocCursor, xParentSection, false );
1589 // Go to the end of the document
1590 mxDocCursor.gotoEnd ( false );
1591 // Insert a new paragraph
1592 mxDocText.insertControlCharacter (
1593 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1594 // And select the new pargraph
1595 xParaCursor.gotoPreviousParagraph ( true );
1597 // Create a new Text Section and access its XNamed interface
1598 XNamed xLinkNamed = UnoRuntime.queryInterface(XNamed.class,
1599 mxDocFactory.createInstance("com.sun.star.text.TextSection"));
1600 // Set the new text section's name to Linked_Section
1601 xLinkNamed.setName ( "Linked_Section" );
1603 // Access the Linked_Section's XTextContent interface
1604 XTextContent xLinkedSection = UnoRuntime.queryInterface(
1605 XTextContent.class, xLinkNamed );
1606 // And insert the Linked_Section into the document
1607 mxDocText.insertTextContent ( mxDocCursor, xLinkedSection, false );
1609 // Access the Linked_Section's XPropertySet interface
1610 XPropertySet xLinkProps = UnoRuntime.queryInterface(
1611 XPropertySet.class, xLinkNamed );
1612 // Set the linked section to be linked to the Child_Section
1613 xLinkProps.setPropertyValue ( "LinkRegion", "Child_Section" );
1615 // Access the XPropertySet interface of the Child_Section
1616 XPropertySet xChildProps = UnoRuntime.queryInterface(
1617 XPropertySet.class, xChildNamed );
1618 // Set the Child_Section's background colour to blue
1619 xChildProps.setPropertyValue( "BackColor", Integer.valueOf(13421823));
1621 // Refresh the document, so the linked section matches the Child_Section
1622 XRefreshable xRefresh = UnoRuntime.queryInterface(
1623 XRefreshable.class, mxDoc );
1624 xRefresh.refresh();
1626 catch (Exception e)
1628 e.printStackTrace();
1632 /** This method demonstrates the XTextColumns interface and how to insert a
1633 blank paragraph using the XRelativeTextContentInsert interface
1635 protected void TextColumnsExample ()
1639 // Go to the end of the document
1640 mxDocCursor.gotoEnd( false );
1641 // insert a new paragraph
1642 mxDocText.insertControlCharacter (
1643 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1645 // insert the string 'I am a fish.' 100 times
1646 for ( int i = 0 ; i < 100 ; ++i )
1648 mxDocText.insertString ( mxDocCursor, "I am a fish.", false );
1650 // insert a paragraph break after the text
1651 mxDocText.insertControlCharacter (
1652 mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false );
1654 // Get the XParagraphCursor interface of our text cursor
1655 XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor );
1656 // Jump back before all the text we just inserted
1657 xParaCursor.gotoPreviousParagraph ( false );
1658 xParaCursor.gotoPreviousParagraph ( false );
1660 // Insert a string at the beginning of the block of text
1661 mxDocText.insertString ( mxDocCursor, "Fish section begins:", false );
1663 // Then select all of the text
1664 xParaCursor.gotoNextParagraph ( true );
1665 xParaCursor.gotoNextParagraph ( true );
1667 // Create a new text section and get its XNamed interface
1668 XNamed xSectionNamed = UnoRuntime.queryInterface(XNamed.class,
1669 mxDocFactory.createInstance("com.sun.star.text.TextSection"));
1671 // Set the name of our new section (appropriately) to 'Fish'
1672 xSectionNamed.setName ( "Fish" );
1674 // Create the TextColumns service and get its XTextColumns interface
1675 XTextColumns xColumns = UnoRuntime.queryInterface(
1676 XTextColumns.class,
1677 mxDocFactory.createInstance ( "com.sun.star.text.TextColumns" ) );
1679 // We want three columns
1680 xColumns.setColumnCount ( (short) 3 );
1682 // Get the TextColumns, and make the middle one narrow with a larger
1683 // margin on the left than the right
1684 TextColumn[] aSequence = xColumns.getColumns ();
1685 aSequence[1].Width /= 2;
1686 aSequence[1].LeftMargin = 350;
1687 aSequence[1].RightMargin = 200;
1688 // Set the updated TextColumns back to the XTextColumns
1689 xColumns.setColumns ( aSequence );
1691 // Get the property set interface of our 'Fish' section
1692 XPropertySet xSectionProps = UnoRuntime.queryInterface(
1693 XPropertySet.class, xSectionNamed );
1695 // Set the columns to the Text Section
1696 xSectionProps.setPropertyValue ( "TextColumns", xColumns );
1698 // Get the XTextContent interface of our 'Fish' section
1699 mxFishSection = UnoRuntime.queryInterface(
1700 XTextContent.class, xSectionNamed );
1702 // Insert the 'Fish' section over the currently selected text
1703 mxDocText.insertTextContent ( mxDocCursor, mxFishSection, true );
1705 // Get the wonderful XRelativeTextContentInsert interface
1706 XRelativeTextContentInsert xRelative = UnoRuntime.queryInterface (
1707 XRelativeTextContentInsert.class, mxDocText );
1709 // Create a new empty paragraph and get its XTextContent interface
1710 XTextContent xNewPara = UnoRuntime.queryInterface(
1711 XTextContent.class,
1712 mxDocFactory.createInstance("com.sun.star.text.Paragraph"));
1714 // Insert the empty paragraph after the fish Text Section
1715 xRelative.insertTextContentAfter ( xNewPara, mxFishSection );
1717 catch (Exception e)
1719 e.printStackTrace();
1724 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */