VB.Net Examples

Hi All, per my username, I am a VB.Net programmer and would prefer to stay that way. I have successfully created a VBNet program (in Visual Studio 2022) which opens various Writer documents that I use as templates to create reports. In this effort, I have used the very good VBNet example found here on the LibreOffice site. Despite a weeks worth of trying, I am unable to implement 4 additional functions of the LO API which would complete the needs I have in creating my reports. If anyone can list VBNet code examples for the following 4 functions I will be most grateful:

  1. Search for Text and Move the (a) cursor to that location in the document
  2. Insert an image (e.g., a JPG) into a table cell (or at a cursor location)
  3. Select and copy a table and paste it to a new location
  4. Select and delete a table

Part 2 of my query to the forum is partially complete. The code is 99% from MS777; I only needed to tweak it a tad to get it to work for me. This VBNet code inserts an image into a Writer Document, yeah! (just not into a TextTable Cell) For those folks using VBNet as I am here’s the code that does this.

Public Shared Sub AddImageToDocument(ByRef strImagePath As String)

	xContext = Bootstrap.bootstrap()
	xServiceManager = DirectCast(xContext.getServiceManager(), XMultiComponentFactory)

	'Create the Desktop
	Dim xDesktop As unoidl.com.sun.star.frame.XDesktop = DirectCast(xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext), unoidl.com.sun.star.frame.XDesktop)

	'Open a new empty writer document
	Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader)
	Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = New unoidl.com.sun.star.beans.PropertyValue() {}
	Dim xComponent As unoidl.com.sun.star.lang.XComponent = xComponentLoader.loadComponentFromURL("private:factory/swriter", "_blank", 0, arProps)
	Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument)

	'Create a text object
	Dim xText As unoidl.com.sun.star.text.XText = xTextDocument.getText()
	Dim xSimpleText As unoidl.com.sun.star.text.XSimpleText = DirectCast(xText, unoidl.com.sun.star.text.XSimpleText)

	'Create a cursor object
	Dim xCursor As unoidl.com.sun.star.text.XTextCursor = xSimpleText.createTextCursor()

	'Inserting some Text
	xText.insertString(xCursor, "The first line in the newly created text document." & vbLf, False)

	'Here starts the image insertion
	Dim image = DirectCast(xComponent, XMultiServiceFactory).createInstance("com.sun.star.text.GraphicObject")
	'Dim image As unoidl.com.sun.star.text.XTextContent = DirectCast(xComponent, XMultiServiceFactory).createInstance("com.sun.star.text.GraphicObject")
	DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("GraphicURL", New uno.Any(GetAbsoluteURI(strImagePath)))
	DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("AnchorType", New uno.Any(GetType(unoidl.com.sun.star.text.TextContentAnchorType), unoidl.com.sun.star.text.TextContentAnchorType.AS_CHARACTER))
	DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("Width", New uno.Any(2500))
	DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("Height", New uno.Any(2500))

	xText.insertTextContent(xCursor, CType(image, unoidl.com.sun.star.text.XTextContent), False)

End Sub

Since this is getting long, I’ll declare this closed and open a new one to query help for my other issues.

Many thanks to elamu, ms777 and robleyd who contributed to my post!

Answer 2:

https://wiki.documentfoundation.org/Macros/Writer/ba002

Thanks for responding and trying to help. Unfortunately the code you sent the link to is for a Macro within Writer. It employs methods that are not available in the API (via VB.Net at least). With the below VB.Net code I am able to load and manipulate a Writer Document (but unable to perform the 4 needed functions I mentioned in my originating post). To better understand the code below, note that each of the objects the code builds fills a shared variable which defines each object/interface. I then employ these objects/interfaces in other modules/classes which have functions specifically for “Tables,” “Frames” etc.

Public Shared Function getExistingWriterFile(ByRef strPathToExistingDocFile As String) As String

    Try
        Dim strFunctionResponse As String = "OK"
        loDocXComponentContext = Bootstrap.bootstrap()
        loXMultiServiceFactory = DirectCast(loDocXComponentContext.getServiceManager(), XMultiServiceFactory)
        loXMultiComponentFactory = DirectCast(loDocXComponentContext.getServiceManager(), XMultiComponentFactory)
        loXDocDesktop = loXMultiServiceFactory.createInstance("com.sun.star.frame.Desktop")
        loDocXComponentLoader = DirectCast(loXDocDesktop, unoidl.com.sun.star.frame.XComponentLoader)
        loDocArProps = {}
        loDocXComponent = loDocXComponentLoader.loadComponentFromURL(GetAbsoluteURI(strPathToExistingDocFile), "_blank", 0, loDocArProps)
        loDocXTextDocument = DirectCast(loDocXComponent, unoidl.com.sun.star.text.XTextDocument)
        loDocFrame = loXMultiServiceFactory.createInstance("com.sun.star.frame.frame")
        loDocXFrame = loXDocDesktop
        loDocXText = loDocXTextDocument.getText
        loDocXTextRange = loDocXTextDocument.getText
        loXDispatchHelper = CType(loXMultiComponentFactory.createInstanceWithContext("com.sun.star.frame.DispatchHelper", loDocXComponentContext), XDispatchHelper)
        loXDispatchProvider = CType(loXMultiComponentFactory.createInstanceWithContext("com.sun.star.frame.XDispatchProvider", loDocXComponentContext), XDispatchProvider)
        loDocXGraphicProvider = CType(loXMultiComponentFactory.createInstanceWithContext("com.sun.star.graphic.GraphicProvider", loDocXComponentContext), XGraphicProvider)
        loDocXTextCursor = loDocXText.createTextCursor()
        Return strFunctionResponse
    Catch ex As System.Exception
        Return "NG"
    Finally
    End Try

End Function

Yes, the code is to be used directly from Writer, but you must use the same methods no matter how much language you use them.

I do not use and I do not like VB.net, but I assure you that you must use the same methods, once you have connected to LibreOffice.

Then I must not be connecting fully or properly, because as I noted, I am able to open a document, add text, modify fonts, and also modify cell properties. But many ‘dot’ methods called out in Pitonyak’s Macro document (and/or used in many other online examples) are not exposed via this (the VBNet) API; hence my unsuccessful week long sojourn through Libre Macro Basic. How can that be?

Here is an example of how to connect to LibreOffice (vb.net). Once properly connected, you can use the API methods and properties documented in the wiki.

https://api.libreoffice.org/examples/CLI/VB.NET/WriterDemo/

elmau, I absolutely want to thank you for helping me!
Sadly the link you sent is to the exact file, which I mentioned in my original post. I have used the code in that file as the basis for writing my own code, again successfully. And by itself, the downloaded code compiled and ran without modification. So it does seem I am connecting properly to the API.
Further, and most frustratingly, I can confirm that there are multiple methods listed in Pitonyak’s document that are associated with various components and interfaces that are not exposed (to me at least) in the API I have. They are not exposed, at least, in the same manner as methods in the example or in any other manner I’ve tried.
All said, I’m still hoping there’s an example of how to perform the four functions I need using VBNet.

Hi,

it is a misbelieve that you cannot access the methods of the interfaces where DirectCast or CType fails. Just go through the standard .NET reflection method. See the xray subroutine in the code below. XRay is very helpful when programming. Of course XRay must be installed prior to usage.

Image insertion (your point 2) is at the end of the main sub.

As I am allergic against VB I got lots of red spots on my skin when typing this. I need to recover now, so be patient when you need additional help …

Good luck,

ms777

'Option Explicit On
'Option Strict On

imports System
imports System.Collections
imports Microsoft.VisualBasic
imports unoidl.com.sun.star.lang
imports unoidl.com.sun.star.uno
imports unoidl.com.sun.star.bridge
imports uno.util

Module WriterDemo

Dim xContext As XComponentContext
Dim xServiceManager As XMultiComponentFactory 'this is XMultiServiceFactory in the OO example

Sub Main( ByVal args() As String)
	System.Console.WriteLine("Start")

	xContext  = Bootstrap.bootstrap()

	xServiceManager = DirectCast(xContext.getServiceManager(), XMultiComponentFactory)

	'Create the Desktop
	Dim xDesktop As unoidl.com.sun.star.frame.XDesktop = DirectCast(xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext), unoidl.com.sun.star.frame.XDesktop)

	'Open a new empty writer document
	Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader)

	Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = New unoidl.com.sun.star.beans.PropertyValue(){}
	Dim xComponent As unoidl.com.sun.star.lang.XComponent = xComponentLoader.loadComponentFromURL( "private:factory/swriter", "_blank", 0, arProps)

	Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument)

	'Create a text object
	Dim xText As unoidl.com.sun.star.text.XText = xTextDocument.getText()
	Dim xSimpleText As unoidl.com.sun.star.text.XSimpleText = DirectCast(xText, unoidl.com.sun.star.text.XSimpleText)

	'Create a cursor object
	Dim xCursor As unoidl.com.sun.star.text.XTextCursor = xSimpleText.createTextCursor()

	'Inserting some Text
	xText.insertString(xCursor, "The first line in the newly created text document." & vbLf, false)

'	xray(xText)
	
' here starts the image insertion
	Dim image = DirectCast(xComponent, XMultiServiceFactory).createInstance("com.sun.star.text.GraphicObject")

    DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("GraphicURL", New uno.Any("file:///C:/Users/Martin/Desktop/pic.png"))
    DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("AnchorType", New uno.Any(GetType(unoidl.com.sun.star.text.TextContentAnchorType), unoidl.com.sun.star.text.TextContentAnchorType.AS_CHARACTER))
    DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("Width", New uno.Any(2500))
    DirectCast(image, unoidl.com.sun.star.beans.XPropertySet).setPropertyValue("Height", New uno.Any(2500))

	xray(image)
	
    xText.insertTextContent(xCursor, image, False)
	

End Sub

Sub xray(target)
    Dim mspf = xServiceManager.createInstanceWithContext("com.sun.star.script.provider.MasterScriptProviderFactory", xContext)

	Dim tSPF = GetType(unoidl.com.sun.star.script.provider.XScriptProviderFactory)
	Dim mCreateScriptProvider = tSPF.GetMethod("createScriptProvider")
	Dim scriptProvider = mCreateScriptProvider.invoke(mspf, New Object(){New uno.Any("")})

	Dim tXScriptProvider = GetType(unoidl.com.sun.star.script.provider.XScriptProvider)
	Dim mGetScript = tXScriptProvider.GetMethod("getScript")
	Dim script = mGetScript.invoke(scriptProvider, New Object(){"vnd.sun.star.script:XrayTool._Main.Xray?language=Basic&location=application"})
	
	Dim tXScript = GetType(unoidl.com.sun.star.script.provider.XScript)
	Dim mInvoke = tXScript.GetMethod("invoke")

	Dim args1 as uno.Any() = New uno.Any(){New uno.Any(GetType(Object), target)}
	Dim args2 as Int16() = New Int16(){}
	Dim args3 as uno.Any() = New uno.Any(){}

	mInvoke.invoke(script, New Object() {args1, args2, args3})
End Sub

End Module

ms777 Thanks! Your Code ~Almost~ compiles. It is fine until you declare the variable ‘image.’ You declare it as an object (by default since you do not set it to any named Type) which the compiler accepts, but the LOC
xText.insertTextContent(xCursor, image, False) fails saying that the LOC wants the variable to be type ‘XTextContent’ and not an Object. Changing/addition types just amplify the compilers complaints.

The code then declares an error at the LOC
Sub xray(target)
The VisualStudio IDE won’t accept ‘target’ without defining its Type in the Sub’s declaration.

Finally, you cite ‘XRay’ as an important tool in programming. I’ve not heard of it. I Googled it and the limited hits I got described it as a debugging tool… Could you please describe XRay a bit better, perhaps include a link to some pages which detail its value and usage?

And finally, I apologize for asking you to wade back into a pool of ‘hot’ VBNet code, I do appreciate your willingness to suffer the allergic reactions!! I’d send you some powerful antihistamines if I could!! :slight_smile:

The home page for Xray seems to have gone away; however you might consider:

There is a Tutorial on MRI which might also be informative.

MS777!! OK!!! So I played around with your code and I was able to get it to work!

But all I did (in addition to providing a path to one of my own local images) was to modify the last LOC in the Main Sub to become the following:
xText.insertTextContent(xCursor, CType(image, unoidl.com.sun.star.text.XTextContent), False)

I’m now going to try and insert an image into a Table Cell by playing around with Cursors.