Difference between revisions of "PyUNO samples"

From Apache OpenOffice Wiki
Jump to: navigation, search
(createTable())
m
(11 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 +
{{Documentation/Candidate}}
 
OpenOffice.org comes with a set of scripts that work as a sample on how to programmatically generate certain tasks using PyUNO.
 
OpenOffice.org comes with a set of scripts that work as a sample on how to programmatically generate certain tasks using PyUNO.
  
 
=== Hello World.py ===
 
=== Hello World.py ===
This script print a Hello World in an Writer document. This uses the XText interface, the actual content is on the String value of the XTextRange.  
+
This script print a Hello World in an Writer document. This uses the [http://api.openoffice.org/docs/common/ref/com/sun/star/text/XText.html XText] interface, the actual content is on the String value of the [http://api.openoffice.org/docs/common/ref/com/sun/star/text/XTextRange.html XTextRange].
<code>[python]
+
 
 +
First step we define the HelloWorldPython() class, then we call the XSCRIPTCONTEXT which will let us work within a sub-environment from UNO. Notice we didn't import uno and we don't need to connect to OOo through the socket. Also we have the uno environment by calling getDocument().
 +
 
 +
Then we call the XText interface to call on the END and STRING methods to write up the "Hello World (in Python)".
 +
<source lang=python>
 
# HelloWorld python script for the scripting framework
 
# HelloWorld python script for the scripting framework
  
Line 17: Line 22:
 
     tRange.String = "Hello World (in Python)"
 
     tRange.String = "Hello World (in Python)"
 
     return None
 
     return None
</code>
+
</source>
  
 
=== Capitalize.py ===
 
=== Capitalize.py ===
This script will show how to modify existing content in a document. More specifically manipulate the format values from the text. We use common python string menthods like '''isupper, upper, len and lower'''. And we use XSCRIPTCONTEXT (Learn about the [http://api.openoffice.org/docs/DevelopersGuide/ScriptingFramework/ScriptingFramework.xhtml XSCRIPTCONTEXT]) for the positioning of the text ([http://api.openoffice.org/docs/common/ref/com/sun/star/text/XText.html XText] and [http://api.openoffice.org/docs/common/ref/com/sun/star/text/XTextRange.html XTextRange] ), the control of the cursor ([http://api.openoffice.org/docs/common/ref/com/sun/star/text/XWordCursor.html xWordCursor]) and xSelectionSupplier in order to select the content.
+
This script will show how to modify existing content in a document. More specifically manipulate the format values from the text. We use common python string methods like '''isupper, upper, len and lower'''. And we use XSCRIPTCONTEXT (Learn about the [http://api.openoffice.org/docs/DevelopersGuide/ScriptingFramework/ScriptingFramework.xhtml XSCRIPTCONTEXT]) for the positioning of the text ([http://api.openoffice.org/docs/common/ref/com/sun/star/text/XText.html XText] and [http://api.openoffice.org/docs/common/ref/com/sun/star/text/XTextRange.html XTextRange] ), the control of the cursor ([http://api.openoffice.org/docs/common/ref/com/sun/star/text/XWordCursor.html xWordCursor]).
  
<code>[python]
+
<source lang=python>
 
# helper function
 
# helper function
 
def getNewString( theString ) :
 
def getNewString( theString ) :
     if( not theString or len(theString) ==0) :
+
     if not theString or len(theString) ==0 :
 
         return ""
 
         return ""
 
     # should we tokenize on "."?
 
     # should we tokenize on "."?
 
     if theString[0].isupper() and len(theString)>=2 and theString[1].isupper() :
 
     if theString[0].isupper() and len(theString)>=2 and theString[1].isupper() :
 
# first two chars are UC => first UC, rest LC
 
# first two chars are UC => first UC, rest LC
         newString=theString[0:1].upper() + theString[1:].lower();
+
         newString=theString.capitalize();
 
     elif theString[0].isupper():
 
     elif theString[0].isupper():
 
# first char UC => all to LC
 
# first char UC => all to LC
Line 40: Line 45:
 
def capitalisePython( ):  
 
def capitalisePython( ):  
 
     """Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case..."""
 
     """Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case..."""
    import string
 
  
 
     # The context variable is of type XScriptContext and is available to
 
     # The context variable is of type XScriptContext and is available to
Line 52: Line 56:
 
     xIndexAccess = xSelectionSupplier.getSelection()
 
     xIndexAccess = xSelectionSupplier.getSelection()
 
     count = xIndexAccess.getCount();
 
     count = xIndexAccess.getCount();
     if(count>=1): #ie we have a selection
+
     for i in range(count) :
         i=0
+
         xTextRange = xIndexAccess.getByIndex(i);
while i < count :
+
        #print "string: " + xTextRange.getString();
            xTextRange = xIndexAccess.getByIndex(i);
+
        theString = xTextRange.getString();
            #print "string: " + xTextRange.getString();
+
        if len(theString)==0 :
            theString = xTextRange.getString();
+
            # sadly we can have a selection where nothing is selected
            if len(theString)==0 :
+
            # in this case we get the XWordCursor and make a selection!
                # sadly we can have a selection where nothing is selected
+
            xText = xTextRange.getText();
                # in this case we get the XWordCursor and make a selection!
+
            xWordCursor = xText.createTextCursorByRange(xTextRange);
                xText = xTextRange.getText();
+
            if not xWordCursor.isStartOfWord():
                xWordCursor = xText.createTextCursorByRange(xTextRange);
+
                xWordCursor.gotoStartOfWord(False);
                if not xWordCursor.isStartOfWord():
+
            xWordCursor.gotoNextWord(True);
                    xWordCursor.gotoStartOfWord(False);
+
            theString = xWordCursor.getString();
                xWordCursor.gotoNextWord(True);
+
            newString = getNewString(theString);
                theString = xWordCursor.getString();
+
            if newString :
                newString = getNewString(theString);
+
                xWordCursor.setString(newString);
                if newString :
+
                xSelectionSupplier.select(xWordCursor);
                    xWordCursor.setString(newString);
+
        else :
                    xSelectionSupplier.select(xWordCursor);
+
            newString = getNewString( theString );
            else :
+
            if newString:
 
+
                xTextRange.setString(newString);
                newString = getNewString( theString );
+
                xSelectionSupplier.select(xTextRange);
                if newString:
+
                    xTextRange.setString(newString);
+
                    xSelectionSupplier.select(xTextRange);
+
    i+= 1
+
  
  
 
# lists the scripts, that shall be visible inside OOo. Can be omitted, if
 
# lists the scripts, that shall be visible inside OOo. Can be omitted, if
# all functions shall be visible, however here getNewString shall be surpressed
+
# all functions shall be visible, however here getNewString shall be suppressed
 
g_exportedScripts = capitalisePython,
 
g_exportedScripts = capitalisePython,
</code>
+
</source>
  
 
=== TableSample.py ===
 
=== TableSample.py ===
Line 91: Line 91:
 
The first step is to get the functions for generating the document, and the other for manipulating the content. The document and content is under the '''createTable()''', while '''insertTextIntoCell()''' will handle the positioning within the table.
 
The first step is to get the functions for generating the document, and the other for manipulating the content. The document and content is under the '''createTable()''', while '''insertTextIntoCell()''' will handle the positioning within the table.
  
<code>[python]
+
<source lang=python>
 
import uno
 
import uno
  
Line 188: Line 188:
  
 
g_exportedScripts = createTable,
 
g_exportedScripts = createTable,
</code>
+
</source>
  
First step to understand is that the UNO module will give us the IDL binding from the API. We will then import specific things from the UNO module. For tht we need to specify the path from com.sun.star and import the interfaces and services.  
+
First step to understand is that the UNO module will give us the IDL binding from the API. We will then import specific things from the UNO module. For that we need to specify the path from com.sun.star and import the interfaces and services.  
  
 
The nested modules [http://api.openoffice.org/docs/common/ref/com/sun/star/text/module-ix.html text] we had: [http://api.openoffice.org/docs/common/ref/com/sun/star/text/ControlCharacter.html ControlCharacter], [http://api.openoffice.org/docs/common/ref/com/sun/star/text/TextContentAnchorType.html TextContentAnchorType] and import [http://api.openoffice.org/docs/common/ref/com/sun/star/text/ControlCharacter.html#PARAGRAPH_BREAK PARAGRAPH_BREAK], [http://api.openoffice.org/docs/common/ref/com/sun/star/text/TextContentAnchorType.html#AS_CHARACTER AS_CHARACTER].
 
The nested modules [http://api.openoffice.org/docs/common/ref/com/sun/star/text/module-ix.html text] we had: [http://api.openoffice.org/docs/common/ref/com/sun/star/text/ControlCharacter.html ControlCharacter], [http://api.openoffice.org/docs/common/ref/com/sun/star/text/TextContentAnchorType.html TextContentAnchorType] and import [http://api.openoffice.org/docs/common/ref/com/sun/star/text/ControlCharacter.html#PARAGRAPH_BREAK PARAGRAPH_BREAK], [http://api.openoffice.org/docs/common/ref/com/sun/star/text/TextContentAnchorType.html#AS_CHARACTER AS_CHARACTER].
Line 198: Line 198:
 
Finally [http://api.openoffice.org/docs/common/ref/com/sun/star/lang/module-ix.html lang] nested module which is about , we import [http://api.openoffice.org/docs/common/ref/com/sun/star/lang/XMain.html XMain].
 
Finally [http://api.openoffice.org/docs/common/ref/com/sun/star/lang/module-ix.html lang] nested module which is about , we import [http://api.openoffice.org/docs/common/ref/com/sun/star/lang/XMain.html XMain].
  
<code>[python]
+
<source lang=python>
 
import uno
 
import uno
  
Line 206: Line 206:
 
from com.sun.star.awt import Size
 
from com.sun.star.awt import Size
  
from com.sun.star.lang import XMain</code>
+
from com.sun.star.lang import XMain
 +
</source>
  
 
==== createTable() ====
 
==== createTable() ====
Line 219: Line 220:
 
* insert a string
 
* insert a string
  
This let us analyze in more detail the interfaces and methods from the cursor, table, text, textFrame and textInTextFrame. All this documentation can be found on the IDL reference. Following this script will allow us to use the IDL to our benefit and explore other nested modules for different porpouse.
+
This let us analyze in more detail the interfaces and methods from the cursor, table, text, textFrame and textInTextFrame. All this documentation can be found on the IDL reference. Following this script will allow us to use the IDL to our benefit and explore other nested modules for different purpose.
  
 
The following values goes extract from the following:
 
The following values goes extract from the following:
Line 228: Line 229:
 
* table = doc.'''createInstance( "com.sun.star.text.TextTable" )'''
 
* table = doc.'''createInstance( "com.sun.star.text.TextTable" )'''
  
The '''loadcomponentFromURL()''' creates and load the Writer document by generating the variable. Text is a variable that will get the document object with the module of Text. The function of '''createTextCursor()''' acording with the IDL ''a new instance of a TextCursor service which can be used to travel in the given text context''.
+
The '''loadcomponentFromURL()''' creates and load the Writer document by generating the variable. Text is a variable that will get the document object with the module of Text. The function of '''createTextCursor()''' according with the IDL ''a new instance of a TextCursor service which can be used to travel in the given text context''.
 
+
<source lang=python>
 +
    """creates a new writer document and inserts a table with some data (also known as the SWriter sample)"""
 +
    ctx = uno.getComponentContext()
 +
    smgr = ctx.ServiceManager
 +
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
 +
   
 +
    # open a writer document
 +
    doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
 +
   
 +
    text = doc.Text
 +
    cursor = text.createTextCursor()
 +
    text.insertString( cursor, "The first line in the newly created text document.\n", 0 )
 +
    text.insertString( cursor, "Now we are in the second line\n" , 0 )</source>
 
The next instance is the creation of the table instance within the table variable. We use the function of '''createTextCursor()''', the path to the module is '''com.sun.star.text.TextTable'''.
 
The next instance is the creation of the table instance within the table variable. We use the function of '''createTextCursor()''', the path to the module is '''com.sun.star.text.TextTable'''.
 
+
<source lang=python>
 +
    # create a text table
 +
    table = doc.createInstance( "com.sun.star.text.TextTable" )
 +
</source>
 
We create our table by using the method '''initialize''' on the line 35 of the code '''table.initialize( 4,4)'''. Now we will deal with the properties of the table as well as the methods and objects from the table like rows, cursor and values. First step after initialize the table, we use the function '''insertTextContent( cursor, table, 0 )''', if you think that this will put a cursor in the table, then you are RIGHT. TextContent is basically an object which can be anchored in a text, like instances of TextFrame or TextFields. In our case we will deal with Cells rather than Frames or Fields.
 
We create our table by using the method '''initialize''' on the line 35 of the code '''table.initialize( 4,4)'''. Now we will deal with the properties of the table as well as the methods and objects from the table like rows, cursor and values. First step after initialize the table, we use the function '''insertTextContent( cursor, table, 0 )''', if you think that this will put a cursor in the table, then you are RIGHT. TextContent is basically an object which can be anchored in a text, like instances of TextFrame or TextFields. In our case we will deal with Cells rather than Frames or Fields.
 +
<source lang=python>
  
 +
    # with 4 rows and 4 columns
 +
    table.initialize( 4,4)
 +
 +
    text.insertTextContent( cursor, table, 0 )
 +
    rows = table.Rows</source>
 
The next point is we will focus on the '''styles''' of the table and have methods such as '''setPropertyValue''' which could might as well be setStyleValue being implemented to the text, for example '''setPropertyValue( "BackTransparent", uno.Bool(0) )''' or '''setPropertyValue( "BackColor", 6710932 )'''.
 
The next point is we will focus on the '''styles''' of the table and have methods such as '''setPropertyValue''' which could might as well be setStyleValue being implemented to the text, for example '''setPropertyValue( "BackTransparent", uno.Bool(0) )''' or '''setPropertyValue( "BackColor", 6710932 )'''.
 +
<source lang=python>
 +
    table.setPropertyValue( "BackTransparent", uno.Bool(0) )
 +
    table.setPropertyValue( "BackColor", 13421823 )
 +
    row = rows.getByIndex(0)
 +
    row.setPropertyValue( "BackTransparent", uno.Bool(0) )
 +
    row.setPropertyValue( "BackColor", 6710932 )</source>
 +
The next step is to get the header of the table which will use the other class and will insert the values that we need, we get '''insertTextIntoCell( table, "A1", "FirstColumn", textColor )''' put color and content into the specific cells from the table object. The syntax is rather straight forward by stating object, cell position, text content and finally text color value which in this case is a variable of the hex color 16777215.
 +
<source lang=python>
 +
    textColor = 16777215
 +
 +
    insertTextIntoCell( table, "A1", "FirstColumn", textColor )
 +
    insertTextIntoCell( table, "B1", "SecondColumn", textColor )
 +
    insertTextIntoCell( table, "C1", "ThirdColumn", textColor )
 +
    insertTextIntoCell( table, "D1", "SUM", textColor )</source>
 +
Now we will insert the content of our table including the numerical value and '''formula'''. We use an array of values and then generate a series of inserting the '''values()''' within the the '''getCellByName()''', '''setValue()''' and '''setFormula'''.
 +
<source lang=python>
 +
    values = ( (22.5,21.5,121.5),
 +
              (5615.3,615.3,-615.3),
 +
              (-2315.7,315.7,415.7) )
 +
    table.getCellByName("A2").setValue(22.5)
 +
    table.getCellByName("B2").setValue(5615.3)
 +
    table.getCellByName("C2").setValue(-2315.7)
 +
    table.getCellByName("D2").setFormula("sum <A2:C2>")</source>
  
 
==== insertTextIntoCell() ====
 
==== insertTextIntoCell() ====
 
This is a sub-process class which brings the services and methods for the table manipulation. The function uses the method getCellbyName, createTextCursor and createPropertyValue.
 
This is a sub-process class which brings the services and methods for the table manipulation. The function uses the method getCellbyName, createTextCursor and createPropertyValue.
 +
 +
This insertTextIntoCell() function will bring a structure to format the header of the table.
 +
 +
 +
[[Category:Python]]
 +
[[Category:Uno]]
 +
[[Category:Tutorial]]

Revision as of 09:24, 25 February 2010

OpenOffice.org comes with a set of scripts that work as a sample on how to programmatically generate certain tasks using PyUNO.

Hello World.py

This script print a Hello World in an Writer document. This uses the XText interface, the actual content is on the String value of the XTextRange.

First step we define the HelloWorldPython() class, then we call the XSCRIPTCONTEXT which will let us work within a sub-environment from UNO. Notice we didn't import uno and we don't need to connect to OOo through the socket. Also we have the uno environment by calling getDocument().

Then we call the XText interface to call on the END and STRING methods to write up the "Hello World (in Python)".

# HelloWorld python script for the scripting framework
 
def HelloWorldPython( ):
    """Prints the string 'Hello World(in Python)' into the current document"""
#get the doc from the scripting context which is made available to all scripts
    model = XSCRIPTCONTEXT.getDocument()
#get the XText interface
    text = model.Text
#create an XTextRange at the end of the document
    tRange = text.End
#and set the string
    tRange.String = "Hello World (in Python)"
    return None

Capitalize.py

This script will show how to modify existing content in a document. More specifically manipulate the format values from the text. We use common python string methods like isupper, upper, len and lower. And we use XSCRIPTCONTEXT (Learn about the XSCRIPTCONTEXT) for the positioning of the text (XText and XTextRange ), the control of the cursor (xWordCursor).

# helper function
def getNewString( theString ) :
    if not theString or len(theString) ==0 :
        return ""
    # should we tokenize on "."?
    if theString[0].isupper() and len(theString)>=2 and theString[1].isupper() :
	# first two chars are UC => first UC, rest LC
        newString=theString.capitalize();
    elif theString[0].isupper():
	# first char UC => all to LC
        newString=theString.lower()
    else: # all to UC.
        newString=theString.upper()
    return newString;
 
def capitalisePython( ): 
    """Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case..."""
 
    # The context variable is of type XScriptContext and is available to
    # all BeanShell scripts executed by the Script Framework
    xModel = XSCRIPTCONTEXT.getDocument()
 
    #the writer controller impl supports the css.view.XSelectionSupplier interface
    xSelectionSupplier = xModel.getCurrentController()
 
    #see section 7.5.1 of developers' guide
    xIndexAccess = xSelectionSupplier.getSelection()
    count = xIndexAccess.getCount();
    for i in range(count) :
        xTextRange = xIndexAccess.getByIndex(i);
        #print "string: " + xTextRange.getString();
        theString = xTextRange.getString();
        if len(theString)==0 :
            # sadly we can have a selection where nothing is selected
            # in this case we get the XWordCursor and make a selection!
            xText = xTextRange.getText();
            xWordCursor = xText.createTextCursorByRange(xTextRange);
            if not xWordCursor.isStartOfWord():
                xWordCursor.gotoStartOfWord(False);
            xWordCursor.gotoNextWord(True);
            theString = xWordCursor.getString();
            newString = getNewString(theString);
            if newString :
                xWordCursor.setString(newString);
                xSelectionSupplier.select(xWordCursor);
        else :
            newString = getNewString( theString );
            if newString:
                xTextRange.setString(newString);
                xSelectionSupplier.select(xTextRange);
 
 
# lists the scripts, that shall be visible inside OOo. Can be omitted, if
# all functions shall be visible, however here getNewString shall be suppressed
g_exportedScripts = capitalisePython,

TableSample.py

On this script we abandon the XSCRIPTCONTEXT and use the UNO module. We also use nested modules from Text, AWT, and LANG. Since we using the UNO module we have to import what we need straight from the com.sun.star path.

The first step is to get the functions for generating the document, and the other for manipulating the content. The document and content is under the createTable(), while insertTextIntoCell() will handle the positioning within the table.

import uno
 
# a UNO struct later needed to create a document
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
from com.sun.star.awt import Size
 
from com.sun.star.lang import XMain
 
def insertTextIntoCell( table, cellName, text, color ):
    tableText = table.getCellByName( cellName )
    cursor = tableText.createTextCursor()
    cursor.setPropertyValue( "CharColor", color )
    tableText.setString( text )
 
 
def createTable():
    """creates a new writer document and inserts a table with some data (also known as the SWriter sample)""" 
    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
 
    # open a writer document
    doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
 
    text = doc.Text
    cursor = text.createTextCursor()
    text.insertString( cursor, "The first line in the newly created text document.\n", 0 )
    text.insertString( cursor, "Now we are in the second line\n" , 0 )
 
    # create a text table
    table = doc.createInstance( "com.sun.star.text.TextTable" )
 
    # with 4 rows and 4 columns
    table.initialize( 4,4)
 
    text.insertTextContent( cursor, table, 0 )
    rows = table.Rows
 
    table.setPropertyValue( "BackTransparent", uno.Bool(0) )
    table.setPropertyValue( "BackColor", 13421823 )
    row = rows.getByIndex(0)
    row.setPropertyValue( "BackTransparent", uno.Bool(0) )
    row.setPropertyValue( "BackColor", 6710932 )
 
    textColor = 16777215
 
    insertTextIntoCell( table, "A1", "FirstColumn", textColor )
    insertTextIntoCell( table, "B1", "SecondColumn", textColor )
    insertTextIntoCell( table, "C1", "ThirdColumn", textColor )
    insertTextIntoCell( table, "D1", "SUM", textColor )
 
    values = ( (22.5,21.5,121.5),
              (5615.3,615.3,-615.3),
              (-2315.7,315.7,415.7) )
    table.getCellByName("A2").setValue(22.5)
    table.getCellByName("B2").setValue(5615.3)
    table.getCellByName("C2").setValue(-2315.7)
    table.getCellByName("D2").setFormula("sum <A2:C2>")
 
    table.getCellByName("A3").setValue(21.5)
    table.getCellByName("B3").setValue(615.3)
    table.getCellByName("C3").setValue(-315.7)
    table.getCellByName("D3").setFormula("sum <A3:C3>")
 
    table.getCellByName("A4").setValue(121.5)
    table.getCellByName("B4").setValue(-615.3)
    table.getCellByName("C4").setValue(415.7)
    table.getCellByName("D4").setFormula("sum <A4:C4>")
 
 
    cursor.setPropertyValue( "CharColor", 255 )
    cursor.setPropertyValue( "CharShadowed", uno.Bool(1) )
 
    text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
    text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 )
    text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
 
    textFrame = doc.createInstance( "com.sun.star.text.TextFrame" )
    textFrame.setSize( Size(15000,400))
    textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER )
 
    text.insertTextContent( cursor, textFrame, 0 )
 
    textInTextFrame = textFrame.getText()
    cursorInTextFrame = textInTextFrame.createTextCursor()
    textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 )
    textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0)
    text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
 
    cursor.setPropertyValue( "CharColor", 65536 )
    cursor.setPropertyValue( "CharShadowed", uno.Bool(0) )
 
    text.insertString( cursor, " That's all for now !!" , 0 )
 
g_exportedScripts = createTable,

First step to understand is that the UNO module will give us the IDL binding from the API. We will then import specific things from the UNO module. For that we need to specify the path from com.sun.star and import the interfaces and services.

The nested modules text we had: ControlCharacter, TextContentAnchorType and import PARAGRAPH_BREAK, AS_CHARACTER.

From awt which is a user interface toolkit had: Size

Finally lang nested module which is about , we import XMain.

import uno
 
# a UNO struct later needed to create a document
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
from com.sun.star.awt import Size
 
from com.sun.star.lang import XMain

createTable()

We can divide this class into the process of:

  • creating a new window
  • creating a writer document
  • inserting text (previously seen on the Hello World Script).
  • Creating a table within the writer document
  • manipulate the format and finally the content
  • Then we insert a frame with text in it
  • insert a string

This let us analyze in more detail the interfaces and methods from the cursor, table, text, textFrame and textInTextFrame. All this documentation can be found on the IDL reference. Following this script will allow us to use the IDL to our benefit and explore other nested modules for different purpose.

The following values goes extract from the following:

  • doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
  • text = doc.Text
  • cursor = text.createTextCursor()
  • table = doc.createInstance( "com.sun.star.text.TextTable" )

The loadcomponentFromURL() creates and load the Writer document by generating the variable. Text is a variable that will get the document object with the module of Text. The function of createTextCursor() according with the IDL a new instance of a TextCursor service which can be used to travel in the given text context.

    """creates a new writer document and inserts a table with some data (also known as the SWriter sample)""" 
    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
 
    # open a writer document
    doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
 
    text = doc.Text
    cursor = text.createTextCursor()
    text.insertString( cursor, "The first line in the newly created text document.\n", 0 )
    text.insertString( cursor, "Now we are in the second line\n" , 0 )

The next instance is the creation of the table instance within the table variable. We use the function of createTextCursor(), the path to the module is com.sun.star.text.TextTable.

    # create a text table
    table = doc.createInstance( "com.sun.star.text.TextTable" )

We create our table by using the method initialize on the line 35 of the code table.initialize( 4,4). Now we will deal with the properties of the table as well as the methods and objects from the table like rows, cursor and values. First step after initialize the table, we use the function insertTextContent( cursor, table, 0 ), if you think that this will put a cursor in the table, then you are RIGHT. TextContent is basically an object which can be anchored in a text, like instances of TextFrame or TextFields. In our case we will deal with Cells rather than Frames or Fields.

    # with 4 rows and 4 columns
    table.initialize( 4,4)
 
    text.insertTextContent( cursor, table, 0 )
    rows = table.Rows

The next point is we will focus on the styles of the table and have methods such as setPropertyValue which could might as well be setStyleValue being implemented to the text, for example setPropertyValue( "BackTransparent", uno.Bool(0) ) or setPropertyValue( "BackColor", 6710932 ).

    table.setPropertyValue( "BackTransparent", uno.Bool(0) )
    table.setPropertyValue( "BackColor", 13421823 )
    row = rows.getByIndex(0)
    row.setPropertyValue( "BackTransparent", uno.Bool(0) )
    row.setPropertyValue( "BackColor", 6710932 )

The next step is to get the header of the table which will use the other class and will insert the values that we need, we get insertTextIntoCell( table, "A1", "FirstColumn", textColor ) put color and content into the specific cells from the table object. The syntax is rather straight forward by stating object, cell position, text content and finally text color value which in this case is a variable of the hex color 16777215.

    textColor = 16777215
 
    insertTextIntoCell( table, "A1", "FirstColumn", textColor )
    insertTextIntoCell( table, "B1", "SecondColumn", textColor )
    insertTextIntoCell( table, "C1", "ThirdColumn", textColor )
    insertTextIntoCell( table, "D1", "SUM", textColor )

Now we will insert the content of our table including the numerical value and formula. We use an array of values and then generate a series of inserting the values() within the the getCellByName(), setValue() and setFormula.

    values = ( (22.5,21.5,121.5),
              (5615.3,615.3,-615.3),
              (-2315.7,315.7,415.7) )
    table.getCellByName("A2").setValue(22.5)
    table.getCellByName("B2").setValue(5615.3)
    table.getCellByName("C2").setValue(-2315.7)
    table.getCellByName("D2").setFormula("sum <A2:C2>")

insertTextIntoCell()

This is a sub-process class which brings the services and methods for the table manipulation. The function uses the method getCellbyName, createTextCursor and createPropertyValue.

This insertTextIntoCell() function will bring a structure to format the header of the table.

Personal tools