6

I'm trying to insert an image into a libreoffice document that is handled/controlled by unotools.

Therefore I start LibreOffice with this command:

soffice --accept='socket,host=localhost,port=8100;urp;StarOffice.Service'

Inside my python code I can connect to LibreOffice:

from unotools import Socket, connect
from unotools.component.writer import Writer
context = connect(Socket('localhost', 8100))
writer = Writer(context)

(This code is taken from this documentation: https://pypi.org/project/unotools/)

By using writer.set_string_to_end() I can add some text to the document. But I also want to insert an image into the document. So far I couldn't find any resource where this was done. The image is inside of my clipboard, so ideally I want to insert the image directly from there. Alternatively I can save the image temporarily and insert the saved file.

Is there any known way how to insert images by using unotools? Any alternative solution would also be great.

SerAlejo
  • 473
  • 2
  • 13

1 Answers1

4

I've found a way to insert images by using uno instead of unotools:

import uno
from com.sun.star.awt import Size
from pythonscript import ScriptContext

def connect_to_office():
    if not 'XSCRIPTCONTEXT' in globals():
        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
                         'com.sun.star.bridge.UnoUrlResolver', localContext )
        client = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext" )
        global XSCRIPTCONTEXT
        XSCRIPTCONTEXT = ScriptContext(client, None, None)

def insert_image(doc):
    size = Size()
    path = uno.systemPathToFileUrl('/somepath/image.png')
    draw_page = self.doc.DrawPage
    image = doc.createInstance( 'com.sun.star.drawing.GraphicObjectShape')
    image.GraphicURL = path
    draw_page.add(image)
    size.Width = 7500
    size.Height = 5000
    image.setSize(size)
    image.setPropertyValue('AnchorType', 'AT_FRAME')

connect_to_office()
doc = XSCRIPTCONTEXT.getDocument()
insert_image(doc)

sources:

  1. https://ask.libreoffice.org/en/question/38844/how-do-i-run-python-macro-from-the-command-line/

  2. https://forum.openoffice.org/en/forum/viewtopic.php?f=45&t=80302

I still don't know how to insert an image from my clipboard, I worked around that problem by saving the image first. If someone knows a way to insert the image directly from the clipboard that would still be helpful.

SerAlejo
  • 473
  • 2
  • 13