PyUNO samples

From Apache OpenOffice Wiki
Revision as of 20:55, 24 May 2007 by Jza (Talk | contribs)

Jump to: navigation, search comes with a set of scripts that work as a sample on how to programmatically generate certain tasks using PyUNO.


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. [python]

  1. HelloWorld python script for the scripting framework

def HelloWorldPython( ):

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

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 XSCRIPTCONTEXT) for the positioning of the text (XText and XTextRange ), the control of the cursor (xWordCursor) and xSelectionSupplier in order to select the content.


  1. 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[0:1].upper() + theString[1:].lower();
   elif theString[0].isupper():

# first char UC => all to LC

   else: # all to UC.
   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..."""
   import string
   # 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();
   if(count>=1):  #ie we have a selection

while i < 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():
               theString = xWordCursor.getString();
               newString = getNewString(theString);
               if newString :
           else :
               newString = getNewString( theString );
               if newString:

i+= 1

  1. lists the scripts, that shall be visible inside OOo. Can be omitted, if
  2. all functions shall be visible, however here getNewString shall be surpressed

g_exportedScripts = capitalisePython,

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 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.

[python] import uno

  1. a UNO struct later needed to create a document

from import PARAGRAPH_BREAK from import AS_CHARACTER from import Size

from 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( "",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( "" )
   # 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),
             (-2315.7,315.7,415.7) )
   table.getCellByName("D2").setFormula("sum <A2:C2>")
   table.getCellByName("D3").setFormula("sum <A3:C3>")
   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( "" )
   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 tht we need to specify the path from 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.

[python] import uno

  1. a UNO struct later needed to create a document

from import PARAGRAPH_BREAK from import AS_CHARACTER from import Size

from import XMain

Personal tools