[Python] De-select image or image is overlapping

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
fmj1988
Posts: 1
Joined: Mon Dec 10, 2018 11:03 pm

[Python] De-select image or image is overlapping

Post by fmj1988 »

The problem for me is basically that after insert a image, the cursor is selected the image and I can't put the cursor into page again.

Here comes the post I put a few weeks into internet:
I have a code that add a image, but it add the second image at the top of the first image.Its overlaps the second on top of first.

PoC_officer.py:

Code: Select all

import os
import uno
import time
import wget

from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK


def getData(url):
    #Dados CSV
    try:
        URL= wget.download(url)
    except Exception as e:
        print("getData>Error ao baixar")
        import pdb; pdb.set_trace()
        exit(10)
    return URL


def Start():
    os.system('/usr/lib/libreoffice/program/soffice --writer --norestore --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" "/home/felipe/workspace/nwi_prtg/Modelo.odt" &')
    time.sleep(3)



def insertImage(MODEL,DISPATCHER,FILENAME):
    from com.sun.star.beans import PropertyValue
    from pathlib import Path
    
    L =  [ PropertyValue() for i in range(4)]
     
    L[0].Name="FileName"
    L[0].Value=str(Path().absolute())+'/'+str(FILENAME['IMG'])
    print (L[0].Value)
    L[1].Name="FilterName"
    L[1].Value="<All formats>"
    L[2].Name = "AsLink"
    L[2].Value = False
    L[3].Name="Style"
    L[3].Value="Graphics"
    DISPATCHER.executeDispatch(MODEL.getCurrentController(), ".uno:InsertGraphic", "", 0, tuple(L))


def getModel(): 
    import pyuno
      # get the uno component context from the PyUNO runtime
    localContext = pyuno.getComponentContext()
     
    # create the UnoUrlResolver
    resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
     
    # connect to the running office
    context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
    manager = context.ServiceManager
    
    # get the central desktop object
    desktop = manager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
         
    #cria dispatcher
    dispatcher = manager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", context)
    
    # access the current writer document
    return desktop.getCurrentComponent()

def getModelANDDispatcher(): 
      # 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)
     
    try:
        context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
#    except com.sun.star.connection.NoConnectException: 
#        print ("Possivel erro no socket")
#        pass
    except Exception as e:
        if (str(e.typeName)=='com.sun.star.connection.NoConnectException'): 
            print("Possible error on socket")
            exit(3)
        else:
            print ("Error unknown")
            print("ERROR:",e)
            exit(4)
        
        
    manager = context.ServiceManager
    
    # get the central desktop object
    desktop = manager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
    model = desktop.getCurrentComponent()
         
    #cria dispatcher
    dispatcher = manager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", context)
    
    # access the current writer document
    if (model == None):
        print("possible error on cursor location")
        exit(5)
    
    return (model,dispatcher)

def getModelANDDispatcherANDDesktop(): 
      # 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)
     
    try:
        context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
#    except com.sun.star.connection.NoConnectException: 
#        print ("Possivel erro no socket")
#        pass
    except Exception as e:
        if (str(e.typeName)=='com.sun.star.connection.NoConnectException'): 
            print("Possible error on socket")
            exit(3)
        else:
            print ("Error unknown")
            print("ERROR:",e)
            exit(4)
        
        
    manager = context.ServiceManager
    
    # get the central desktop object
    desktop = manager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
    model = desktop.getCurrentComponent()
         
    #cria dispatcher
    dispatcher = manager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", context)
    
    # access the current writer document
    if (model == None):
        print("possible error on cursor location")
        exit(5)
    
    return (model,dispatcher,desktop)
 
 
def prepareDocumentMultiple(FILENAME=[]): 

    from com.sun.star.beans import PropertyValue
    import os
    import pdb
    #import pdb; pdb.set_trace()
    #model,dispatcher = getModelANDDispatcher()
    model,dispatcher,desktop = getModelANDDispatcherANDDesktop()
    text = model.Text
    tRange = text.End
    cursor = text.createTextCursor()
    for f in FILENAME:
        pdb.set_trace()
        #text.insertControlCharacter( cursor, PARAGRAPH_BREAK, False )
        #cursor.gotoEnd(False)
        insertImage(model,dispatcher,{'IMG':f})
        #text.insertString( cursor, '\n\n\n\n\n\n\n', False )
        text.insertControlCharacter( cursor, PARAGRAPH_BREAK, False )
        text.insertControlCharacter( cursor, PARAGRAPH_BREAK, False )
        text.insertControlCharacter( cursor, PARAGRAPH_BREAK, False )
        text.insertControlCharacter( cursor, PARAGRAPH_BREAK, False )
        cursor.gotoEnd(False)
    #print(">>>Iniciando debugger")
    #import pdb; pdb.set_trace()

starter.py:

Code: Select all

 import PoC_officer as POF
    
IMAGES=['https://unsplash.com/photos/aEtl64kP8mk/download?force=true',
    'https://i.pinimg.com/originals/c6/a2/89/c6a289648d689ebf779f5c11b2699ab5.jpg']
    
L=[]
POF.Start()
    
for i in IMAGES:
    print("Download a imaagem")
    img=POF.getData(i)
    print("Add to the list")
    L.append(img)
POF.prepareDocumentMultiple(L)
as suggest in another post I did put the break, but without sucess.

Code: Select all

   text.insertControlCharacter( cursor, PARAGRAPH_BREAK, False )
   cursor.gotoEnd(False)
as a workaround, I first insert the first image, then I set the cursor at the end of the file and continue the code.

How to Run:

Code: Select all

    python3.6 starter.py
    (Pdb) c
    "First image is inserted and I select the cursor at the end of file"
    (Pdb) c
    "It is put the second Image"
OpenOffice 6.0 / Ubuntu 18.04 64Bits
flock3
Posts: 1
Joined: Mon Dec 17, 2018 10:03 am

Re: [Python] De-select image or image is overlapping

Post by flock3 »

I have the same problem. Been looking for a solution for too long. Did you found a solution? Because your workaround didn't work for me. Thanks!
OpenOffice 5.2.7.2 on Debian 9
hubert lambert
Posts: 145
Joined: Mon Jun 13, 2016 10:50 am

Re: [Python] De-select image or image is overlapping

Post by hubert lambert »

Hi,

The dispatcher makes only use of gui command urls, that is the commands sent by menu items, tool bar buttons and so on.
This way, inserting images is always done at the view cursor position.
For your code to work, you need either:
- to move the view cursor instead of the api text cursor ;
- to use the uno api instead of the dispatcher.

Regards.
AOOo 4.1.2 on Win7 | LibreOffice on various Linux systems
Post Reply