Manuel Nunes
Manuel Nunes

Reputation: 5

Libreoffice get bookmark insert in text

In LibreOffice is it possible to get bookmark that is inserted in the text?

With the code below I can get the list of all the bookmarks I have available, but I just wanted the ones that are actually inserted in the text.

XBookmarksSupplier xBookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, xCurrentComponent); XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks();

Upvotes: 0

Views: 418

Answers (1)

JohnSUN
JohnSUN

Reputation: 2539

Hope this helps:

Sub MyBookmarks
Dim oBookmarks As Variant
Dim oElementNames As Variant
Dim oBookmark As Variant
Dim oTextFields As Variant
Dim oEnum As Variant
Dim oTextField As Variant
Dim sSourceName As String
Dim i As Long, j As Long 
Dim sResult As String
Rem First step - collect Bookmarks
    oBookmarks = ThisComponent.getBookmarks()
    oElementNames = oBookmarks.getElementNames()
Rem Create list of Bookmarks to count Text Fields with it
    ReDim oBookmark(LBound(oElementNames) To UBound(oElementNames))
    For i = LBound(oElementNames) To UBound(oElementNames)
        oBookmark(i) = Array(oElementNames(i),0)
    Next i
Rem Enumerate Text Fields
    oTextFields = ThisComponent.getTextFields()
    oEnum = oTextFields.createEnumeration()
    Do While oEnum.hasMoreElements()
        oTextField = oEnum.nextElement()
        sSourceName = oTextField.SourceName
        For i = LBound(oBookmark) To UBound(oBookmark)
            If oBookmark(i)(0) = sSourceName Then
                oBookmark(i)(1) = oBookmark(i)(1) + 1
                Exit For
            EndIf 
        Next i
    Loop
Rem Show results    
    sResult = ""
    For i = LBound(oBookmark) To UBound(oBookmark)
        If oBookmark(i)(1) > 0 Then
            sResult = sResult + oBookmark(i)(0) + " (" + oBookmark(i)(1) + ")" + Chr(10)
        EndIf 
    Next i
    If Len(sResult) > 0 Then
        sResult = Left(sResult, Len(sResult)-1)
        MsgBox("The text of the document uses Bookmarks:" + Chr(10) + sResult, MB_ICONINFORMATION, "Used Bookmarks")
    Else
        MsgBox("No Bookmarks are used in the text of the document", MB_ICONEXCLAMATION, "No Bookmarks")
    EndIf 
    
    sResult = ""
    For i = LBound(oBookmark) To UBound(oBookmark)
        If oBookmark(i)(1) = 0 Then
            sResult = sResult + oBookmark(i)(0) + ", "
        EndIf 
    Next i
    If Len(sResult) > 0 Then
        MsgBox("Bookmarks that are not used in the text of the document:" + Chr(10) + Left(sResult, Len(sResult)-2), MB_ICONINFORMATION, "Not Used Bookmarks")
    EndIf 
End Sub

Upvotes: 1

Related Questions