OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

Writer Examples
Goto page 1, 2, 3  Next
 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets
View previous topic :: View next topic  
Author Message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Wed Feb 18, 2004 5:20 am    Post subject: Writer Examples Reply with quote

This is a short example program which shows how to...

1. Obtain a Writer document by either....
1A. Create a new one
1B. Open one from disk (both Linux and Windows examples), including loading a Word or RTF file.
1C. Access the current Writer document, assuming that this macro is embedded into a Writer document rather than some other type of document.
1D. Access the frontmost window, which must be a Writer document.

2. Put some content into the document.
2A. Changing the style of a paragraph.
2B. Moving the cursor within a document.

3. Print the document three different ways...
3A. Simple printing via. the API.
3B. Printing via. the API, but with some arguments.
3C. Using the dispatcher to print by displaying the pring job dialog box.

4. Save the Writer document in native OOo format.

5. Export the Writer document to...
* Word
* PDF
* RTF
* HTML

6. Close the document.

This example can serve as a companion to my similar example article for the Calc spreadsheet, which can be found here...
http://www.oooforum.org/forum/viewtopic.php?t=4996

Code:
Sub Main
   '-------
   ' First task is to get some document we want to work with.
   '  The document to work with is assigned to the variable oDoc.
   
   ' Create new writer document.
   oDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array() )
   
   ' Alternately we could have loaded a document from disk like one of these examples....
'   oDoc = StarDesktop.loadComponentFromURL( ConvertToURL( "C:\MyText.sxw" ), "_blank", 0, Array() )
   ' We could even load a Microsoft Word document on Linux.
'   oDoc = StarDesktop.loadComponentFromURL( ConvertToURL( "/home/danny/Desktop/MyText.doc" ), "_blank", 0, Array() )
   ' This example would import a Rich Text Format document.
'   oDoc = StarDesktop.loadComponentFromURL( ConvertToURL( "C:\MyText.rtf" ), "_blank", 0,_
'      Array( _
'         MakePropertyValue( "FilterName", "Rich Text Format" ) )
   ' This example would import an HTML document.
'   oDoc = StarDesktop.loadComponentFromURL( ConvertToURL( "C:\MyText.html" ), "_blank", 0,_
'      Array( _
'         MakePropertyValue( "FilterName", ""HTML (StarWriter)" ) )

   ' Alternately, if this macro code were embedded within a Writer document,
   '  and we wanted to manipulate the document containing this code...
'   oDoc = ThisComponent

   ' Alternately, if we wanted to work with the frontmost window,
   '  which had better be a Writer document!
'   oDoc = StarDesktop.getCurrentComponent()

   ' To learn more about the loadComponentFromURL() method of the desktop object,
   '  then see this article I wrote...
   '    http://www.oooforum.org/forum/viewtopic.php?t=5252

   '
   '-------
   
   
   '-------
   ' Now create some content in the document.
   
   ' Get the text of the document.
   oText = oDoc.getText()
   ' Get a cursor that can move over or to any part of the text.
   oCursor = oText.createTextCursor()
   
   ' Insert text and paragraph breaks into the text, at the cursor position.
   oText.insertString( oCursor, "This is line number 1.", False )
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   oText.insertString( oCursor, "This is line number 2 (in style Heading 2)", False )
   oCursor.ParaStyleName = "Heading 2"
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   oText.insertString( oCursor, "This is line number 3.", False )
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   ' Move the cursor to the start of the document, then insert more text.
   oCursor.gotoStart( False )
   oText.insertString( oCursor, "This line appears at the beginning of the document.", False )
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   '
   '-------
   
   
   '-------
   ' Now print the document

   ' Now print the document.
   ' Print two copies.
   ' Print pages 1 thru 4, and also page 10.
'   oDoc.print( _
'      Array( _
'         MakePropertyValue( "CopyCount", 2 ),_
'         MakePropertyValue( "Pages", "1-4;10" ) ) )
   
   ' Print the document already, without any arguments.
'   oDoc.print( Array() )
   
   ' Print the document by bringing up the Print Job dialog box
   '  for the user to interact with.
   oDocFrame = oDoc.getCurrentController().getFrame()
   oDispatchHelper = createUnoService( "com.sun.star.frame.DispatchHelper" )
   oDispatchHelper.executeDispatch( oDocFrame, ".uno:Print", "", 0, Array() )
   ' To learn some more about the dispatcher, see these articles...
   '    http://www.oooforum.org/forum/viewtopic.php?t=5058
   '    http://www.oooforum.org/forum/viewtopic.php?t=5057

   '
   '-------


   '-------
   ' Now save the document

   ' This is where we will save the document...
   cFolder = "C:\Documents and Settings\dbrewer\Desktop\" ' On Windows
'   cFolder = "/home/danny/Desktop/" ' On Linux
   
   ' Now save the document to disk as a Writer document.
   oDoc.storeToURL( ConvertToURL( cFolder+"Test1.sxw" ), Array() )
   
   ' Now save the document to disk as a Microsoft Word document.
   oDoc.storeToURL( ConvertToURL( cFolder+"Test1.doc" ),_
      Array( _
         MakePropertyValue( "FilterName", "MS Word 97" ) )
   
   ' Now save the document to disk as a PDF.
   oDoc.storeToURL( ConvertToURL( cFolder+"Test1.pdf" ),_
      Array( _
         MakePropertyValue( "FilterName", "writer_pdf_Export" ) )
   
   ' Now save the document to disk as a Rich Text Format document.
   oDoc.storeToURL( ConvertToURL( cFolder+"Test1.rtf" ),_
      Array( _
         MakePropertyValue( "FilterName", "Rich Text Format" ) )
   
   ' Now save the document to disk as an HTML document.
   oDoc.storeToURL( ConvertToURL( cFolder+"Test1.html" ),_
      Array( _
         MakePropertyValue( "FilterName", "HTML (StarWriter)" ) )
   
   ' A list of some filter names you can use for both loading
   '  and saving a document can be found here...
   '    http://www.oooforum.org/forum/viewtopic.php?t=3549
   
   '
   '-------
   
   
   '-------
   ' Now close the document
   oDoc.close( True )
   '-------
End Sub


' The MakePropertyValue() function is defined here...
'   http://www.oooforum.org/forum/viewtopic.php?t=5108
'
Function MakePropertyValue( Optional cName As String, Optional uValue ) As com.sun.star.beans.PropertyValue
   oPropertyValue = createUnoStruct( "com.sun.star.beans.PropertyValue" )
   If Not IsMissing( cName ) Then
      oPropertyValue.Name = cName
   EndIf
   If Not IsMissing( uValue ) Then
      oPropertyValue.Value = uValue
   EndIf
   MakePropertyValue() = oPropertyValue
End Function


The MakePropertyValue() function is defined here...
http://www.oooforum.org/forum/viewtopic.php?t=5108

Hope this is helpful.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu Feb 19, 2004 6:21 am    Post subject: Reply with quote

I would like to improve upon the above example.

Replace the second section with new code. The second section is the part which generates the contents of the document. Look for this code in the above example....
Code:
   '-------
   ' Now create some content in the document.
   
   .......code goes here......

   '
   '-------


Replace it with this...
Code:
   '-------
   ' Now create some content in the document.
   
   ' Get the text of the document.
   oText = oDoc.getText()
   ' Get a cursor that can move over or to any part of the text.
   oCursor = oText.createTextCursor()
   
   ' Note that we could call createTextCursor() multiple times to create more
   '  cursors which can move over the text.
   ' None of these cursors would be visible on the screen.
   'oCursor2 = oText.createTextCursor()
   'oCursor3 = oText.createTextCursor()
   
   ' Insert text.
   oText.insertString( oCursor, "This is line number 1.", False )
   
   ' Insert paragraph break.  There are now two paragraphs, the 2nd one is empty.
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   ' Insert text into 2nd paragraph.  Change paragraph style.
   oText.insertString( oCursor, "This is line number 2 (in style Heading 2)", False )
   oCursor.ParaStyleName = "Heading 2"
   
   ' Insert paragraph break.  There are now three paragraphs, the 3rd one is empty.
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   oText.insertString( oCursor, "This is line number 3.", False )
   
   ' Insert paragraph break.
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   ' Move the cursor to the start of the document.
   oCursor.gotoStart( False )
   
   ' Insert text into beginning of 1st paragraph.
   oText.insertString( oCursor, "This line appears at the beginning of the document.", False )

   ' Insert paragraph break.  This breaks the text we just inserted, and what was the first
   '  paragraph into two paragraphs.  What was paragraph 1 is now paragraph 2.   
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   ' Now we're going to change the text "line number" from "This is line number 3." so that "line number"
   '  is in Bold and Italics.
   ' I'm going to use vertical bars | to show where the cursor is,
   '  or two vertical bars to show a cursor that is expanded over one
   '  or more characters.
   ' Move the cursor to the start of the document.
   oCursor.gotoStart( False )         ' |This line appears at the beginning of the document.
   oCursor.gotoNextParagraph( False )   ' |This is line number 1.
   oCursor.gotoNextParagraph( False )   ' |This is line number 2.
   oCursor.gotoNextParagraph( False )   ' |This is line number 3.
   oCursor.gotoNextWord( False )      ' This |is line number 3.
   oCursor.gotoNextWord( False )      ' This is |line number 3.
   oCursor.gotoNextWord( True )      ' This is |line| number 3.
   ' Note that the word "line" is now selected because of the True parameter.
   ' The True parameter is like holding down the SHFIT key while moving the cursor.
   oCursor.gotoNextWord( True )      ' This is |line number| 3.
   ' Now note that both words "line number" are selected by the cursor.
   oCursor.CharPosture = com.sun.star.awt.FontSlant.ITALIC
   oCursor.CharWeight = com.sun.star.awt.FontWeight.BOLD
   
   ' Now we're going to insert a page break right before "This is line number 2."
   oCursor.gotoStart( False )         ' |This line appears at the beginning of the document.
   oCursor.gotoNextParagraph( False )   ' |This is line number 1.
   oCursor.gotoNextParagraph( False )   ' |This is line number 2.
   ' Now that the cursor is positioned at the very beginning of the desired paragraph,
   '  we can manipulate properties of the paragraph.
   ' One of those properties is page breaks.  Said differently, page breaks in Writer
   '  are actually properties of a paragraph.
   oCursor.BreakType = com.sun.star.style.BreakType.PAGE_BEFORE
   
   ' You might really want to single-step over each line of the above code,
   '  and watch how each statement affects the document.
   
   '
   '-------



References to the API

The Paragraph Service is described here...
http://api.openoffice.org/docs/common/ref/com/sun/star/text/Paragraph.html
As you can see, a Paragraph includes a ParagraphProperties service...
http://api.openoffice.org/docs/common/ref/com/sun/star/style/ParagraphProperties.html
as well as a CharacterProperties service...
http://api.openoffice.org/docs/common/ref/com/sun/star/style/CharacterProperties.html


The ParagraphProperties has some useful properties such as ParaStyleName and BreakType, which are used in the above example.

The CharacterProperties has some useful properties such as CharPosture and CharWeight, which are used in the above example.


The methods, such as gotoStart() are from the interface XTextCursor...
http://api.openoffice.org/docs/common/ref/com/sun/star/text/XTextCursor.html

The methods, such as gotoNextParagraph() are from the interface XParagraphCursor...
http://api.openoffice.org/docs/common/ref/com/sun/star/text/XParagraphCursor.html

The methods, such as gotoNextWord() are from the interface XWordCursor...
http://api.openoffice.org/docs/common/ref/com/sun/star/text/XWordCursor.html

You might also be interested in XSentenceCursor...
http://api.openoffice.org/docs/common/ref/com/sun/star/text/XSentenceCursor.html



All about Cursors

The line that says
oText = oDoc.getText()
assigns to variable oText, the main text of the document.

From this text, we can get one or more cursors, using a statement like this.
oCursor = oText.createTextCursor()
These cursors can move over the document to any position or range of text. A cursor is like the little blinking vertical line that appears in between characters on the screen. Sometimes the cursor is not a line, but a range of characters, such as when you click and drag the mouse to select a word or sentence.

Again, I want to emphasize two points about these cursors...
1. You can create as many of these cursors from the text as you want.
2. None of them are visible on the screen.

There is a cursor that is visible on the screen. It is called the View Cursor. It works the same as these invisible cursors we are creating, but does not have some of the methods, but also has some additional methods.

When you create a cursor using
oCursor = oText.createTextCursor()
that cursor has the following methods...
collapseToStart()
collapseToEnd()
boolean isCollapsed()
boolean goLeft( nNumChars, bExpand )
boolean goRight( nNumChars, bExpand )
gotoStart( bExpand )
gotoEnd( bExpand )
gotoRange( XTextRange, bExpand )
boolean isStartOfWord()
boolean isEndOfWord()
boolean gotoNextWord( bExpand )
boolean gotoPreviousWord( bExpand )
boolean gotoEndOfWord( bExpand )
boolean gotoStartOfWord( bExpand )
boolean isStartOfSentence()
boolean isEndOfSentence()
boolean gotoNextSentence( bExpand )
boolean gotoPreviousSentence( bExpand )
boolean gotoEndOfSentence( bExpand )
boolean gotoStartOfSentence( bExpand )
boolean isStartOfParagraph()
boolean isEndOfParagraph()
boolean gotoNextParagraph( bExpand )
boolean gotoPreviousParagraph( bExpand )
boolean gotoEndOfParagraph( bExpand )
boolean gotoStartOfParagraph( bExpand )

If you have a range of text selected with the cursor, that is, if some text is "hilighted" instead of a blinking bar (but remember, this is invisible on the screen), then calling collapseToStart() or collapseToEnd() will collapse the cursor to a blinking bar that is either at the beginning or end of the range of text that was previously selected.

The function isCollapsed() tells you whether the cursor is a blinking bar (true), or whether the cursor has at least one (or more) characters selected (false - not collapsed).

The functions goLeft() and goRight() move the cursor one character to the left or right by any number of characters.

Many of the remaining cursor functions have a parameter I am calling bExpand. The bExpand parameter if True is like holding down the SHIFT key while moving the cursor. That cause a range of text to be selected. If the cursor is in between two characters, then calling goRight( 1, False ) will collapse the cursor to a blinking bar, and move it one character to the right. But if I had called goRight( 1, True ), then the cursor would expand to now enclose or hilight one character to the right.

Calling gotoRight( 1, False ) is like pressing the RightArrow key on the keyboard.
Calling gotoRight( 1, True ) is like pressing SHIFT-RightArrow key on the keyboard.

The function gotoStart() moves the cursor to the start of the document. If the bExpand parameter is True, then it is like Shift-clicking at the start of the document. Everything from wherever the cursor was to the beginning of the document is now hilighted.

The function gotoRange() moves a cursor to the exact same position or range as some other cursor. If I had created two cursors oCursor1 and oCursor2, and I had moved oCursor2 to some part of the document, then I could move oCursor1 there by calling oCursor1.gotoRange( oCursor2 ). Note that any cursor is an XTextRange, and thus an acceptable parameter to gotoRange().

The remaining functions, such as iSStartOfWord(), gotoNextWord(), etc. should be clear from the above explanation.


Inserting text

The way we inserted anything into the document was by writing something like

oText.insertString( oCursor, "This is line number 3.", False )

You always INSERT something on the Text object, but insert it at one of the cursor positions. Again, the last parameter of insertString is whether the cursor should expand so that the newly inserted text is now hilighted.

The object in the oText variable has these useful methods...
insertString( XTextRange, cNewTextToInsert, bExpand )
insertControlCharacter( XTextRange, nControlCharacter, bExpand )

You've already seen how insertString works. The insertControlCharacter is similar, but instead of passing a string, you pass one of the following...

com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK
com.sun.star.text.ControlCharacter.LINE_BREAK
com.sun.star.text.ControlCharacter.HARD_HYPHEN
com.sun.star.text.ControlCharacter.SOFT_HYPHEN
com.sun.star.text.ControlCharacter.HARD_SPACE
com.sun.star.text.ControlCharacter.APPEND_PARAGRAPH

The above constants are described here in the online API.

The above code example shows the use of insertControlCharacter() to insert several PARAGRAPH_BREAK's.

As we've already seen, the Text object (in variable oText) also has the method createTextCursor(). But it also has a variation of that...

createTextCursorByRange( XTextRange )

THis is similar to createTextCursor(), but the newly created cursor is pre-positioned at some range specified by XTextRange. (Remember previously from the above explanation of the gotoRange() function, I mentioned that any cursor is also an XTextRange.) Since every cursor is also an XTextRange, any cursor is acceptable as a parameter to createTextCursorByRange(). As far as I can tell, the following two code fragments are identical.
Code:
oCursor2 = oText.createTextCursor()
oCursor2.gotoRange( oCursor1 )

and this...
Code:
oCursor2 = oText.createTextCursorByRange( oCursor1 )

Both fragments create a new cursor oCursor2, which is positioned to the same range as oCursor1.

I'll just throw out that the Text object in oText, is also an XTextRange. Therefore, oText is also an acceptable parameter to both gotoRange() and createTextCursorByRange().

The Text object in variable oText also has these two methods, which I'll talk about another time.
insertTextContent( XTextRange, XTextContent, bAbsorb )
removeTextContent( XTextContent )

These methods insert into the text, something called an XTextContent, which I'll write about on another day. XTextContent can be one of...
* A Text object, like we're talking about (i.e. a thing that creates cursors and inserts stuff)
* A table
* A graphic
* A drawing object
* etc...



Briefly about XTextRange...

Both oCursor and oText (variables in the above example code) are an XTextRange.

XTextRange has the following useful methods...
XText getText()
XTextRange getStart()
XTextRange getEnd()
String getString()
setString( cString )

So either a Text or a Cursor have the above methods. On a cursor, for instance, you could call setString(). On the variable oText, you could call setString() and replace the contents of the entire document! Similarly, getString() returns all the content as a String. If you call getString() on the Text of the entire document, you may get an error, because the entire doucment may not fit into a String. But you could call getText() on a cursor that enclosed a small range of text. For example, a smell checker might move the cursor over each individual word of the document, call getString() on each word, then look up the word in the spelling dictionary.

Both getStart() and getEnd() return an XTextRange that describes the position of the start or end of the text. The XTextRange returned by these would be acceptable as a parameter to gotoRange() or createTextCursorByRange(). But bear in mind that the thing returned by calling getStart() or getEnd() is NOT a cursor! It just describes a position in text, like a cursor does, but doesn't not have the features of a cursor described above.

An XTextRange is just an abstract description of some position in the text. Any Cursor is an XTextRange. Any Text is also an XTextRange (therefore the entire document is an XTextRange).

The method getText() simply returns the Text in which the Cursor is positioned. For instance, if you passed variable oCursor to a subroutine, but had not passed in oText, the subroutine could recover oText from the cursor like this...
oText = oCursor.getText()



That's all I'm going to write for now.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
Doe
Guest





PostPosted: Fri Feb 20, 2004 12:38 pm    Post subject: can we instal open office on a different machine Reply with quote

Hi,

We are working on a Java application and we are planning to use open office to do some reports. The java app will be on Sun one App server. Can we install open office on a windows platform and have the Java app call open office for reporting..

any tips will be appreciated.
Back to top
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Feb 20, 2004 6:26 pm    Post subject: Reply with quote

I have personally had a Java app on Linux manipulate an OOo running on Windows, and also vice versa, a Java app on Windows manipulate a running OOo on Linux.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Mon Feb 23, 2004 11:20 am    Post subject: Reply with quote

Here is another article that is closely related to this article.

Altering CharacterProperties of Text
http://www.oooforum.org/forum/viewtopic.php?t=6195
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Mar 05, 2004 11:14 am    Post subject: Reply with quote

Here is a related example...

http://www.oooforum.org/forum/viewtopic.php?p=24245#24245

of inserting a table into a Writer document.

The example, creates a new Writer document.
Inserts a table into it.
Randomly colors the background colors of the cells.
Inserts text into the cells -- using a text cursor.

This example, then also leads to another example showing how to alter the widths of columns of a table in a Writer document.
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Thu Apr 08, 2004 6:49 am; edited 1 time in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu Apr 08, 2004 5:58 am    Post subject: Reply with quote

Here is an example of scanning a Writer document, word by word.

The program uses two cursors. A "scan" cursor scans one word at a time. An "end" cursor is positioned at the end of the document. When the "scan" cursor reaches the beginning range of the "end" cursor, then you know you've reached the end of the document.

Code:
' Iterate over words in document.
' You could instead iterate over sentences, or paragraphs.
Sub Main
   ' ThisComponent must be a Writer document!
   oDoc = ThisComponent
   oText = oDoc.getText()
   
   ' Create a cursor to scan the document word by word.
   oScanCursor = oText.createTextCursor()
   oScanCursor.gotoStart( False )
   
   ' Create a cursor at the very end of the document.
   oEndCursor = oText.createTextCursor()
   oEndCursor.gotoEnd( False )
   
   ' Loop until the "scan" cursor reaches the "end" cursor.
   Do Until oText.compareRegionStarts( oScanCursor, oEndCursor ) = 0
      bCursorMoved = oScanCursor.gotoEndOfWord( True )
      'bCursorMoved = oScanCursor.gotoEndOfSentence( True )
      'bCursorMoved = oScanCursor.gotoEndOfParagraph( True )
      
      If bCursorMoved Then
         cWord = oScanCursor.getString()         
         Print cWord
      EndIf
      
      bCursorMoved = oScanCursor.gotoNextWord( False )
      'bCursorMoved = oScanCursor.gotoNextSentence( False )
      'bCursorMoved = oScanCursor.gotoNextParagraph( False )
   
      If Not bCursorMoved Then
         Exit Do
      EndIf
   Loop
End Sub


Note that you will get empty words (blank strings) on empty paragraphs. This skips right over tables. Presumably it skips over other items (TextContent) as well, such as graphics.
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Wed Jul 28, 2004 6:11 am; edited 2 times in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Apr 16, 2004 6:32 am    Post subject: Reply with quote

Here is an example of scanning a Writer document Sentence by Sentence.

Each sentence is changed to to a different random color.

The program does this....
1. Create new Writer document.
2. Put some text into it.
3. Scan sentence by sentence, changing each sentence to a different random color.

Code:
Sub Main
   oDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array() )
   oText = oDoc.getText()
   oCursor = oText.createTextCursor()
   
   ' Add a bunch of text to the document.
   AddTextToDocument( oCursor )
   
   ' Now scan the document, sentence by sentence.
   ' Change each sentence to a random color.
   oCursor.gotoStart( False )
   Do While oCursor.isStartOfSentence()
      If oCursor.gotoEndOfSentence( True ) Then
         oCursor.CharColor = RGB( Int(Rnd()*150), Int(Rnd()*150), Int(Rnd()*150) )
         oCursor.collapseToEnd()
      EndIf
      Do
         If Not oCursor.gotoNextSentence( False ) Then Exit Do
      Loop Until oCursor.isStartOfSentence()
   Loop
End Sub


Sub AddTextToDocument( oCursor )
   InsertString( oCursor, "If you can't beat your computer at chess, then try switching to kickboxing instead." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Give a man a fish and you feed him for a day." )
   InsertString( oCursor, "  Teach him to use the Internet and keep him occupied for life." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Give a man a fish and you feed him for a day." )
   InsertString( oCursor, "  Teach a man to eat, and he will fish forever." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Give a man a fish and you feed him for a day." )
   InsertString( oCursor, "  Teach a man to fish, you will loose your monopoly on fisheries." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Give a man a fish and you feed him for a day." )
   InsertString( oCursor, "  Teach a man to fish, he will drown when his ship is sunk after being accidentially struck by a US Nuclear submarine." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Give a man a match, you keep him warm for the evening." )
   InsertString( oCursor, "  If you light him on fire, you keep him warm for the rest of his life." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Give a man a fish and you feed him for a day." )
   InsertString( oCursor, "  Teach a man to fish, he will overfish, using progressively more sophisticated technology to kill more than he can eat, decimating the fish population, wrecking havoc up and down the food chain, and destroying the ecology." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Give a man a match, you keep him warm for the evening." )
   InsertString( oCursor, "  Teach a man to fish, you can sell him all kinds of accessories." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "If you must choose between two evils, pick the one you've never tried before." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "Borrow money from pessimists-they don't expect it back." )
   InsertString( oCursor, "  A fool and his money are soon partying." )
   InsertString( oCursor, "  Bills travel through the mail at twice the speed of checks." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "99 percent of lawyers give the rest a bad name." )
   InsertParaBreak( oCursor )
   InsertParaBreak( oCursor )
   InsertString( oCursor, "For a list of the ways that technology has failed to improve our lives, press F13." )
   InsertString( oCursor, "  Error: unable to format drive A:, now formatting drive C: instead." )
End Sub



Sub InsertString( oCursor, cString )
   oText = oCursor.getText()
   oText.insertString( oCursor, cString, False )
End Sub

Sub InsertLineBreak( oCursor )
   oText = oCursor.getText()
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.LINE_BREAK, False )
End Sub

Sub InsertParaBreak( oCursor )
   oText = oCursor.getText()
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
End Sub

Sub InsertPageBreak( oCursor )
   oText = oCursor.getText()
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   oCursor.BreakType = com.sun.star.style.BreakType.PAGE_BEFORE
End Sub

Sub InsertColumnBreak( oCursor )
   oText = oCursor.getText()
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   oCursor.BreakType = com.sun.star.style.BreakType.COLUMN_BEFORE
End Sub

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
tilox
General User
General User


Joined: 10 May 2004
Posts: 12
Location: Thiene (VI) Italy

PostPosted: Mon May 10, 2004 7:29 am    Post subject: Re: can we instal open office on a different machine Reply with quote

Doe wrote:
Hi,

We are working on a Java application and we are planning to use open office to do some reports. The java app will be on Sun one App server. Can we install open office on a windows platform and have the Java app call open office for reporting..

any tips will be appreciated.


So you've already use the Dispatcher under java... Could you explain me some tips to use it??
Back to top
View user's profile Send private message Send e-mail Yahoo Messenger
xslf
OOo Enthusiast
OOo Enthusiast


Joined: 22 Jun 2003
Posts: 128
Location: Israel

PostPosted: Wed May 19, 2004 5:58 pm    Post subject: Reply with quote

First- thanks for the Macro examples. There are a greate help in attempting to learn how to create and use macros.

As I work with both Hebrew and English text, I want to control the directionality of the text (LTR for English text, RTL for Hebrew text).

I see that there is a service that should be able to help me:
http://api.openoffice.org/docs/common/ref/com/sun/star/style/ParagraphPropertiesComplex.html
but I am not sure how to use it.

Would it be possible to get a simple example?

Thanks!
_________________
http://www.xslf.com
Back to top
View user's profile Send private message Visit poster's website
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu May 20, 2004 6:41 am    Post subject: Reply with quote

Here is an example from Cybb20 of how to adjust the page margins of the currently visible page.

http://www.oooforum.org/forum/viewtopic.php?p=33706#33706
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu May 20, 2004 7:07 am    Post subject: Reply with quote

xslf wrote:
As I work with both Hebrew and English text, I want to control the directionality of the text (LTR for English text, RTL for Hebrew text).
I see that there is a service that should be able to help me:
http://api.openoffice.org/docs/common/ref/com/sun/star/style/ParagraphPropertiesComplex.html
but I am not sure how to use it.
Would it be possible to get a simple example?


Here is the best example I could quickly come up with. But I don't know how to test it?

Code:
Sub Main
   ' Create new writer document.
   oDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array() )
   ' Get the text of the document.
   oText = oDoc.getText()
   ' Get a cursor that can move over or to any part of the text.
   oCursor = oText.createTextCursor()
   
   
   ' Insert text.
   oText.insertString( oCursor, "If it ain't broke, then fix it 'till it is.", False )
   ' Insert paragraph break.
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   
   ' Insert text. -- Select all of it by passing TRUE.
   oText.insertString( oCursor, "Failure is not an option... it comes bundled with Windows NT.", True )
   ' Change writing direction of selected text.
   oCursor.WritingMode = com.sun.star.text.WritingMode2.RL_TB
   ' De-select text range.
   oCursor.collapseToEnd()
   ' Insert paragraph break.
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   
   ' Insert text.
   oText.insertString( oCursor, "Lazyness is the first step towards efficiency.", False )
   ' Insert paragraph break.
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
   
   
   ' Insert text.
   oText.insertString( oCursor, "Indecision is the mother of flexibility.", False )
   ' Insert paragraph break.
   oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
End Sub

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Tue Jun 01, 2004 6:22 am    Post subject: Reply with quote

Here are a few more recent examples....


Text Cursors and the View Cursor

Iannz demonstrates how to set the View Cursor to the end of a paragraph.
http://www.oooforum.org/forum/viewtopic.php?t=9348
Remember...
* There is only one View Cursor. It is the one that is visible on the screen. It has less powerful navigation capabilities than a text cursor.
* You can create as many text cursors as you like and independantly navigate them throughout the document. They have powerful navigation capabilities, by character, word, sentence, or by paragraph. Their ranges can be compared. Text cursors are invisible, and not seen on the screen.
* Any cursor (view cursor or text cursor) can be set to the range of any other cursor (view cursor or text cursor).
Using Iannz's technique, and the above information about cursors, you can position the View Cursor anywhere you want it, even if you first have to use a text cursor to properly locate the range that you want to select.


Both Andrew Pitonyak and Iannz answer a question about enumerating the paragraphs that a user has selected with the mouse.
http://www.oooforum.org/forum/viewtopic.php?t=9346
Again, remember that the View Cursor has the user's mouse selection. You can create text cursors and navigate them through the document without disturbing the View Cursor's position.


In this thread
http://www.oooforum.org/forum/viewtopic.php?t=9328
a technique is discussed to insert a line of text, and then set the view cursor to the next line after the inserted text.

==========

Tables

In this thread dfrench shows how to determine the number of rows in a table.
http://www.oooforum.org/forum/viewtopic.php?t=9319

My next example, directly below, shows how to obtain the number of rows and columns of a table.


===========

Page Margins (Page styles)

In this thread
http://www.oooforum.org/forum/viewtopic.php?t=9026
Cybb20 shows how to change the margins of a page. By changing the page style's margins, all pages which share the style get the same margins.

If you need some pages with different margins, then introduce a new page style, set its margins differently, and then set some pages to use the new page style.
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Fri Jun 04, 2004 6:06 am; edited 1 time in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Jun 04, 2004 6:05 am    Post subject: Reply with quote

Here is an example which creates a table in a Writer document. It then changes the border of cells B1:C6 to be a thick bright red border.

Code:

Sub Main
'   oDoc = ThisComponent
   oDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array()

   ' Create a table
   oTable = oDoc.createInstance( "com.sun.star.text.TextTable" )
   ' Initialise table to have seven rows, five columns
   oTable.initialize( 7, 5 )
   
   ' Get view cursor
   oViewCursor = oDoc.getCurrentController().getViewCursor()
   ' Get text of the document.
   oText = oDoc.getText()
   'Insert table into text at current view cursor position.
   oText.insertTextContent( oViewCursor, oTable, False )
   
   ' Now let's have some fun with the table.
   ' Fill in all the cells.
   For nRow = 0 To oTable.getRows().getCount() - 1
      For nCol = 0 To oTable.getColumns().getCount() - 1
         oCell = oTable.getCellByPosition( nCol, nRow )
         
         ' Make the cell a random, but very light color
         oCell.BackColor = RGB( _
               Rnd() * 31 + 224,_
               Rnd() * 31 + 224,_
               Rnd() * 31 + 224 )
         
         ' Get the cell's text.
         oText = oCell.getText()
         ' Get a cursor on the cell's text.
         oCursor = oText.createTextCursor()
         
         ' Insert something random
         oText.insertString( oCursor, "$"+CSTR( Int( Rnd() * 10000 ) ), False )
         
         ' For some rows, make the number format be Currency.
         If nRow <= 3 Then
            oCell.NumberFormat = com.sun.star.util.NumberFormat.CURRENCY
         Else
            oCell.NumberFormat = com.sun.star.util.NumberFormat.TEXT
         EndIf
      Next
   Next
   
   oCells = oTable.getCellRangeByName( "B1:C6" )
   
   oCells.LeftBorder   = MakeCellBorderLine( RGB(255,100,100), 0, 75, 0 )
   oCells.RightBorder  = MakeCellBorderLine( RGB(255,100,100), 0, 75, 0 )
   oCells.TopBorder    = MakeCellBorderLine( RGB(255,100,100), 0, 75, 0 )
   oCells.BottomBorder = MakeCellBorderLine( RGB(255,100,100), 0, 75, 0 )
End Sub

Function MakeCellBorderLine( nColor, nInnerLineWidth, nOuterLineWidth, nLineDistance ) _
         As com.sun.star.table.BorderLine
   oBorderLine = createUnoStruct( "com.sun.star.table.BorderLine" )
   With oBorderLine
      .Color = nColor
      .InnerLineWidth = nInnerLineWidth
      .OuterLineWidth = nOuterLineWidth
      .LineDistance = nLineDistance
   End With
   MakeCellBorderLine = oBorderLine
End Function


I trivially created the above by combining two past examples that I had already written. Total time, about five minutes. (Actually, I spend the bulk of the time preparing this message.)

The bulk of the above code comes from this example of creating a table in writer. (I tweaked the randomization of the colors to get lighter colors.)
http://www.oooforum.org/forum/viewtopic.php?p=24246#24246

Then I took this Calc spreadsheet example, where I modified the cell borders
http://www.oooforum.org/forum/viewtopic.php?p=31118#31118
and used that code to modify the the table borders for this Writer example.

It is really worth your time to look at the above two examples from which this single new example was constructed. Each of the above examples has additional information which I will not repeat here.

Both of the above examples come from these two long threads....

Calc Examples
http://www.oooforum.org/forum/viewtopic.php?t=4996

Writer Examples
http://www.oooforum.org/forum/viewtopic.php?t=6049
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Jun 04, 2004 6:34 am    Post subject: Reply with quote

Here is a discussion with an answer about creating Writer tables with no borders. (One solution I propose is adapted from the above example.)

http://www.oooforum.org/forum/viewtopic.php?p=35476#35476
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets All times are GMT - 8 Hours
Goto page 1, 2, 3  Next
Page 1 of 3

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group