Изображения перекрываются при добавлении - PullRequest
0 голосов
/ 04 декабря 2018

У меня есть код, который добавляет изображение, но оно добавляет второе изображение вверху первого изображения. Оно перекрывает второе сверху первого.

PoC_officer.py:

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/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 prepareDocumentMultiple(FILENAME=[]): 

    from com.sun.star.beans import PropertyValue
    import os
    import pdb
    #import pdb; pdb.set_trace()
    model,dispatcher = getModelANDDispatcher()
    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)

starter.py:

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)

, как подсказывают в другом посте, я поставил разрыв, но без успеха.

   text.insertControlCharacter( cursor, PARAGRAPH_BREAK, False )
   cursor.gotoEnd(False)

в качестве обходного пути, я сначала вставляю первыйизображение, затем я устанавливаю курсор в конец файла и продолжаю код.

Как запустить:

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