Page 1 of 1

[Solved] Python API to replace text with bullet list

Posted: Thu May 23, 2019 11:16 pm
by mtran
I am able to use Python API to search and replace a placeholder text '_myPlaceholder_' in a .odt file.
I now want to replace this placeholder with a bulleted list (i.e. "Solid small circular bullets") with a list read in from a regular text file stored as a python list variable myList.
Here's the code snippet for the search and replace part:

Code: Select all

 import uno

# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()

# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
    "com.sun.star.bridge.UnoUrlResolver", localContext )

# connect to the running office
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )

# get the central desktop object
desktop = ctx.ServiceManager.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
document = desktop.loadComponentFromURL(ODT_FILE ,"_blank", 0, ())

# search and replace
search = document.createSearchDescriptor()
search.SearchString = '_myPlaceholder_'
found = document.findFirst(search)
found.String = found.String.replace('_myPlaceholder_', myList)
So basically, replace my placeholder with a multi line list prepended with the bullet character. I greatly appreciate any help or suggestions!

Re: Python API to replace text with bullet list

Posted: Sun May 26, 2019 11:49 am
by hubert lambert
Hi,

If your place holder is a single paragraph, you could try something like this :

Code: Select all

    [...]
    found = doc.findFirst(search)
    found.String = '\r'.join(myList)
    found.NumberingStyleName = "List 1"
If the place holder is "in line", part of a paragraph text, it is a little bit different has you have to add two paragraph breaks :

Code: Select all

    [...]
    found = doc.findFirst(search)
    T = doc.Text
    T.insertControlCharacter(found.Start, 0, False)
    found.String = '\r'.join(myList)
    currentnumstyle = found.NumberingStyleName
    found.NumberingStyleName = "List 1"
    T.insertControlCharacter(found.End, 0, True)
    found.End.NumberingStyleName = currentnumstyle
Regards.

Re: Python API to replace text with bullet list

Posted: Sun May 26, 2019 8:39 pm
by mtran
Thanks Hubert for providing both cases for separate paragraph and inline replacements!
Also, I was only using \n, as I didn't know about the requirements for \r.

Just curious, would you know where I can find the various NumberingStyleName types?

Re: Python API to replace text with bullet list

Posted: Mon May 27, 2019 8:22 pm
by hubert lambert
Numbering style names are just the one visible in the gui (F11). You can define any new personal style next to the predefined names.

Re: Python API to replace text with bullet list

Posted: Tue May 28, 2019 5:21 am
by mtran
Got it, thanks again!