[Solved] Add custom metadata using InContentMetadata
[Solved] Add custom metadata using InContentMetadata
LibreOffice 24.2.4.2 on Windows, using the Java SDK.
I am trying to find a way to associate custom metadata with individual text paragraphs in a LibreOffice Writer document, which I can construct or manipulate using the SDK. So when adding each paragraph I want the ability to add a custom ID, e.g. 101, 102 or whatever, which I can cross-reference with content in a database, and which is preserved if the document is edited and the paragraphs reordered.
I have found the class com.sun.star.text.InContentMetadata which sounds like it might do what I want, and is documented here:
https://api.libreoffice.org/docs/idl/re ... adata.html
However I cannot seem to find this in the SDK from my Java environment. My Java IDE is picking up "libreoffice.jar" from C:\Program Files\LibreOffice\program\classes, and if I open that Jar it does not contain this class (nor a number of other documented classes).
Does that class exist, if so do you know why I am not picking that up in the SDK - are there additional Jars I need to import to access the full set of classes? And if it does exist, are there any code examples or documentation of how to use this?
Thanks.
I am trying to find a way to associate custom metadata with individual text paragraphs in a LibreOffice Writer document, which I can construct or manipulate using the SDK. So when adding each paragraph I want the ability to add a custom ID, e.g. 101, 102 or whatever, which I can cross-reference with content in a database, and which is preserved if the document is edited and the paragraphs reordered.
I have found the class com.sun.star.text.InContentMetadata which sounds like it might do what I want, and is documented here:
https://api.libreoffice.org/docs/idl/re ... adata.html
However I cannot seem to find this in the SDK from my Java environment. My Java IDE is picking up "libreoffice.jar" from C:\Program Files\LibreOffice\program\classes, and if I open that Jar it does not contain this class (nor a number of other documented classes).
Does that class exist, if so do you know why I am not picking that up in the SDK - are there additional Jars I need to import to access the full set of classes? And if it does exist, are there any code examples or documentation of how to use this?
Thanks.
Last edited by Hagar Delest on Thu Dec 12, 2024 6:33 pm, edited 2 times in total.
Reason: tagged solved.
Reason: tagged solved.
LibreOffice 24.2 on Windows
Re: Add Custom Metadata using InContentMetadata
Hi, the easiest way to get support is to prepare a minimum sample in OO Basic and then ask for help with translating to Java
Re: Add Custom Metadata using InContentMetadata
What kind of LibreOffice document? Writer?
Each paragraph already has a metadata reference which uniquely identifies it though I don't know how persistent that reference is.
Edit:
to make it your own reference number you'd just need a lookup table somewhere with your number stored beside it.
Edits can easily remove a paragraph though.
Each paragraph already has a metadata reference which uniquely identifies it though I don't know how persistent that reference is.
Edit:
to make it your own reference number you'd just need a lookup table somewhere with your number stored beside it.
Edits can easily remove a paragraph though.
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add Custom Metadata using InContentMetadata
Thanks, yes, Writer.JeJe wrote: Wed Nov 20, 2024 3:13 pm What kind of LibreOffice document? Writer?
Each paragraph already has a metadata reference which uniquely identifies it though I don't know how persistent that reference is.
If I open the saved document content in content.xml within the .odt, I don't see a unique reference, I see things like this:
Code: Select all
<text:p text:style-name="Text_20_body">It was the best of times, it was the worst of times ...</text:p>LibreOffice 24.2 on Windows
Re: Add Custom Metadata using InContentMetadata
You're right, its lost on saving so that's no use.
You could try ParaUserDefinedAttributes but my past experience suggests this may be prone to problems. Other methods would be bookmarks, or hidden text perhaps.
ParaUserDefinedAttributes, based on Zizi64's code from
viewtopic.php?t=111531
Saved in content.xml
You could try ParaUserDefinedAttributes but my past experience suggests this may be prone to problems. Other methods would be bookmarks, or hidden text perhaps.
ParaUserDefinedAttributes, based on Zizi64's code from
viewtopic.php?t=111531
Code: Select all
sub TestParaUserDefinedAttributes
p= thiscomponent.text.createenumeration.nextelement
Dim oUserData 'A copy of the UserDefinedAttributes
Dim oMyAttribute As New com.sun.star.xml.AttributeData
Dim oAttribute
Dim oDoc
'oDoc = createNewCalcDoc() REM-ed by Zizi64
oDoc = Thiscomponent 'Inserted by Zizi64
oMyAttribute.Type = "CDATA"
oMyAttribute.Value = "Andrew Pitonyak"
REM Here is where things usually go wrong with a statement like
REM oCell.UserDefinedAttributes.insertByName("Andy", oMyAttribute)
REM This fails every time. Instead, first make a copy and then
REM operate on the copy.
oUserData = p.ParaUserDefinedAttributes
If NOT oUserData.hasByName("Andy") Then
oUserData.insertByName("Andy", oMyAttribute)
p.ParaUserDefinedAttributes = oUserData
End If
oAttribute = p.ParaUserDefinedAttributes.getByName("Andy")
'Xray oCell
Print oAttribute.Value
End Sub
<style:style style:name="P1" style:family="paragraph" style:parent-style-name="Heading_20_3">
<style:paragraph-properties Andy="Andrew Pitonyak"/>
</style:style>
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add Custom Metadata using InContentMetadata
Thanks, unfortunately I can't see ParaUserDefinedAttributes exposed in the Java SDK either.JeJe wrote: Wed Nov 20, 2024 7:12 pm You could try ParaUserDefinedAttributes but my past experience suggests this may be prone to problems. Other methods would be bookmarks, or hidden text perhaps.
Bookmarks, yes, should be straightforward, but obviously those would be visible to users editing the document, so would have potential either to get manipulated by the user, or just to look very cluttered if it was a long document with hundreds of paragraphs and a bookmark entry for each one.
LibreOffice 24.2 on Windows
Re: Add Custom Metadata using InContentMetadata
OK, I don't have much experience of OO Basic, but I've managed to create an example which seems to do roughly what I want:ms777 wrote: Wed Nov 20, 2024 12:19 am Hi, the easiest way to get support is to prepare a minimum sample in OO Basic and then ask for help with translating to Java
Code: Select all
Sub Main
Dim oDocument As Object
Dim oCursor As Object
Dim oMeta1 As Object
Dim oMeta2 As Object
oDocument = ThisComponent
oCursor = oDocument.Text.createTextCursor()
oDocument.Text.insertString(oCursor, "Text para 1", false)
oMeta1 = oDocument.createInstance("com.sun.star.text.InContentMetadata")
oDocument.Text.insertTextContent(oCursor, oMeta1, False)
oDocument.Text.insertControlCharacter(oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false)
oDocument.Text.insertString(oCursor, "Text para 2", false)
oMeta2 = oDocument.createInstance("com.sun.star.text.InContentMetadata")
oDocument.Text.insertTextContent(oCursor, oMeta2, False)
oDocument.Text.insertControlCharacter(oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false)
End Sub
Code: Select all
<text:p text:style-name="P12">
Text para 1
<text:meta xml:id="id738995083"/>
</text:p>
<text:p text:style-name="P12">
Text para 2
<text:meta xml:id="id209415548"/>
</text:p>
At the moment the IDs it inserts are just random, I haven't figured out how to set those to (or link them to) specific values that I want, but I assume that is possible.
So anyway my question is can I do the above using the Java SDK. At the moment as I said it appears like the InContentMetadata interface is not exposed in the Java SDK, and therefore I suspect this is not possible.
LibreOffice 24.2 on Windows
- MrProgrammer
- Moderator
- Posts: 5479
- Joined: Fri Jun 04, 2010 7:57 pm
- Location: Wisconsin, USA
Re: Add custom metadata using InContentMetadata
Perhaps this page will help. If so, we hope you will post a working example of setting specific values.
Documentation → DevGuide → RDF metadata
Documentation → DevGuide → RDF metadata
Mr. Programmer
AOO 4.1.7 Build 9800, MacOS 13.7.8, iMac Intel. The locale for any menus or Calc formulas in my posts is English (USA).
AOO 4.1.7 Build 9800, MacOS 13.7.8, iMac Intel. The locale for any menus or Calc formulas in my posts is English (USA).
Re: Add custom metadata using InContentMetadata
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
Note, your code creates an InContentMetadata text portion with an empty string... you can see this with MRI or by using a left or right arrow key over where you inserted it (the arrow key will stop in place at that position and need to be pressed again to move)... and it can be deleted by the user like anything else in the document.
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
Hi,
the translation to Java is not too difficult. The major problem is to understand how to operate the rdf api. I tried a bit, but with no success
Good luck,
ms777
the translation to Java is not too difficult. The major problem is to understand how to operate the rdf api. I tried a bit, but with no success
Good luck,
ms777
Code: Select all
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.XInterface;
public final class AOO {
public static void main(String[] args) {
try {
XComponentContext xContext = Bootstrap.bootstrap();
com.sun.star.lang.XMultiComponentFactory xMCF = xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, oDesktop);
PropertyValue[] loadProps = new PropertyValue[0];
XComponent xComponent = xCompLoader.loadComponentFromURL("private:factory/swriter", "_blank", 0, loadProps);
XTextDocument oTextDocument = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, xComponent);
com.sun.star.text.XText xText = oTextDocument.getText();
com.sun.star.text.XTextCursor oCursor = xText.createTextCursor();
xText.insertString( oCursor, "Text para 1", false );
XMultiServiceFactory oMultiServiceFactory = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, xComponent);
XInterface oMeta = (XInterface) oMultiServiceFactory.createInstance("com.sun.star.text.InContentMetadata");
XTextContent oMeta1 = (XTextContent) UnoRuntime.queryInterface(XTextContent.class, oMeta);
xText.insertTextContent(oCursor, oMeta1, false);
xText.insertControlCharacter(oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Re: Add custom metadata using InContentMetadata
You can use ensureMetadataReference after which the paragraph id is saved to the file and looks to persist while the paragraph does.
Code: Select all
p = thiscomponent.text.createenumeration.nextelement
p.ensureMetadataReference
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
And having used ensureMetadataReference (and kept a copy of that information) we can find the paragraph again (or other referenced object) with
Awesome... something I thought was missing/inaccessible but its available.
Code: Select all
thiscomponent.getElementByMetadataReference(the reference as StringPair)
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
Access looks to be via thiscomponent.RDFRepository if that's any help.ms777 wrote: Fri Nov 22, 2024 9:20 pm The major problem is to understand how to operate the rdf api. I tried a bit, but with no success
extending the earlier basic code...
Code: Select all
graph = oDocument.RDFRepository.creategraph(oMeta1)
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
So creating an rdf graph with one statement for the first paragraph in the document, in Basic:
Code: Select all
p= thiscomponent.text.createenumeration.nextelement 'get first para in document
pURI = createunoservicewitharguments("com.sun.star.rdf.URI", array(p.stringvalue)) 'create a URI for it
with thiscomponent.RDFRepository
stringURI = createunoservicewitharguments("com.sun.star.rdf.URI", array("http://www.w3.org/2001/XMLSchema-datatypes#string"))
literal = createunoservicewitharguments("com.sun.star.rdf.Literal", array("My string value of this literal"))
'.destroygraph(pURI) 'destroy if a graph for paragraph already exists
graph =.creategraph(pURI)
graph.addstatement(pURI,stringURI,literal) 'add statement
mri .getStatements(pURI,NULL,NULL) 'get all statements for paragraph
end with
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
Cool ... and is it saved to the document?
Re: Add custom metadata using InContentMetadata
Excellent, thanks, I've got that working in my Java app now too!
I'll try combining with JeJe's RDF example. I've had a couple of goes at understanding the "RDF Graph" stuff, I'll try again
LibreOffice 24.2 on Windows
Re: Add custom metadata using InContentMetadata
Unfortunately, the rdf graphs and statements, though saved, appear to be lost when the document is reloaded - in both OO and LO.
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
ParaUserDefinedAttributes look to fare better.
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
This is bad news! I was just getting a nice little Java example working (using LibreOffice Writer), adding the required metadata to each paragraph, which I could see saved as metadata graph files when I opened the .odt file contents.JeJe wrote: Wed Nov 27, 2024 2:26 pm Unfortunately, the rdf graphs and statements, though saved, appear to be lost when the document is reloaded - in both OO and LO.
But I get the same result as you - if I open and close the document without saving, the metadata graph contents are still there, but if I save it, they're gone
LibreOffice 24.2 on Windows
Re: Add custom metadata using InContentMetadata
The RDFRepository has importGraph and exportGraph methods which might be the basis of a workaround... exporting before closing and importing on file opening (assuming those work).
Another workaround might be your own routines to export/import to a neighbouring text file, or before closing storing the information elsewhere in the document such as a document property, or perhaps a hidden and protected textsection.
Another workaround might be your own routines to export/import to a neighbouring text file, or before closing storing the information elsewhere in the document such as a document property, or perhaps a hidden and protected textsection.
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
It just seems weird that the metadata is destroyed if you open and save the document, doesn't it? Given it's all there in the file and stored in the proper RDF format and everything - but seems useless if it doesn't persist.
I've had a look at ParaUserDefinedAttributes. I've managed to get a Java example working with that, to add some custom attributes to each paragraph:
That works, the attributes are saved if I open and re-save the document. But looking at how they are saved in content.xml, this results in new, custom styles being created for each paragraph, with those attributes saved as part of the styles:
So I think this is really intended for describing custom information about a style, which fits with the documentation, which says ParagraphProperties "describes the style of paragraphs". So it doesn't feel right to use that to store arbitrary metadata about a paragraph. There might be a limit to how many custom styles can be created, so this might break for large documents. More importantly, I've proven that if you manually edit the document and change the style of a paragraph to something else, that information is lost.
I've had a look at ParaUserDefinedAttributes. I've managed to get a Java example working with that, to add some custom attributes to each paragraph:
Code: Select all
XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xTextElement);
Object userAttrsObj = xPropertySet.getPropertyValue("ParaUserDefinedAttributes");
XNameContainer userAttrs = UnoRuntime.queryInterface(XNameContainer.class, userAttrsObj);
AttributeData attrib = new AttributeData();
attrib.Type = "String";
attrib.Value = Integer.toString(count + 100);
userAttrs.insertByName("id", attrib);
attrib = new AttributeData();
attrib.Type = "String";
attrib.Value = "davide";
userAttrs.insertByName("owner", attrib);
xPropertySet.setPropertyValue("ParaUserDefinedAttributes", userAttrs);
Code: Select all
<style:style style:name="P1" style:family="paragraph" style:parent-style-name="Text_20_body">
<style:paragraph-properties id="102" owner="davide"/>
</style:style>
<style:style style:name="P2" style:family="paragraph" style:parent-style-name="Text_20_body">
<style:paragraph-properties id="103" owner="davide"/>
</style:style>
<style:style style:name="P3" style:family="paragraph" style:parent-style-name="Text_20_body">
<style:paragraph-properties id="104" owner="davide"/>
</style:style>
...
LibreOffice 24.2 on Windows
Re: Add custom metadata using InContentMetadata
Reading the documentation,
"Adding metadata to a document" here:
https://wiki.openoffice.org/wiki/Docume ... F_metadata
The answer may be you have to use addMetadataFile:
https://www.openoffice.org/api/docs/com ... tadataFile
"Adding metadata to a document" here:
https://wiki.openoffice.org/wiki/Docume ... F_metadata
The answer may be you have to use addMetadataFile:
https://www.openoffice.org/api/docs/com ... tadataFile
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
And I used .creategraph(pURI) where pURI was a URI based on the paragraph's stringvalue. It may be that a named graph doesn't have to be that, but can be any name? Not being reloaded seems more likely me doing something(s) wrong rather than a bug.
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
The same thing happens if direct formatting is applied to paragraphs, in content.xml we get style:name="P1". "P2" and if direct formatting is applied to text its "T1", "T2".ellisdp wrote: Thu Nov 28, 2024 3:34 pm That works, the attributes are saved if I open and re-save the document. But looking at how they are saved in content.xml, this results in new, custom styles being created for each paragraph, with those attributes saved as part of the styles:
So I think this is really intended for describing custom information about a style, which fits with the documentation, which says ParagraphProperties "describes the style of paragraphs". So it doesn't feel right to use that to store arbitrary metadata about a paragraph. There might be a limit to how many custom styles can be created, so this might break for large documents. More importantly, I've proven that if you manually edit the document and change the style of a paragraph to something else, that information is lost.
In the navigator there's no new paragraph style created, the original name remains, so its just that paragraph being modified. The attributes don't seem to be lost when direct formatting is applied to the paragraph, but yes, are with a style change... interesting.<style:style style:name="P1" style:family="paragraph" style:parent-style-name="Standard">
<style:paragraph-properties fo:margin-top="0.9cm" fo:margin-bottom="0cm"/>
</style:style>
<style:style style:name="P2" style:family="paragraph" style:parent-style-name="Standard">
<style:paragraph-properties fo:margin-top="9.999cm" fo:margin-bottom="0cm"/>
</style:style>
<style:style style:name="T1" style:family="text">
<style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
</style:style>
<style:style style:name="T2" style:family="text">
<style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"/>
</style:style>
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
I want to point your attention to https://opengrok.libreoffice.org/xref/c ... 8819f2#321 . It looks like you can / have to generate a new file (custom.rdf) inside the writer doc to store the data
Re: Add custom metadata using InContentMetadata
addMetadataFile works, this creates "MyRDFFile" which persists in the document on reopening.
(That creates the file as is but Array() should to be "a list of types that will be inserted as rdf:type properties for the graph.")
Code: Select all
graphname = ThisComponent.addMetadataFile("MyRDFFile",array())
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
I'm not following the "rdf:type properties" bit for that array, but this seems to work:
Code: Select all
Sub CreateInCMetadataAtCursor()
with thiscomponent
IC = .createInstance("com.sun.star.text.InContentMetadata")
vc = .currentcontroller.viewcursor
vc.Text.insertTextContent(vc, IC, False)
graphname = .addMetadataFile("MyRDFFile",array(IC)
graph =.RDFRepository.getGraph(graphname)
Predicate = createunoservicewitharguments("com.sun.star.rdf.URI", array("#Predicate"))
literal = createunoservicewitharguments("com.sun.star.rdf.Literal", array("Literal string as Object"))
graph.addstatement(IC,Predicate,literal)
mri .getMetadataGraphsWithType(IC)(0)
'metadata from viewcursor
IC= vc.NestedTextContent
mri .RDFRepository.getStatements(IC,NULL,NULL)
end with
end sub
Windows 10, Openoffice 4.1.11, LibreOffice 7.4.0.3 (x64)
Re: Add custom metadata using InContentMetadata
Thanks, I have got this working in my Java app now too. This creates a metadata graph in a new, custom file "customMeta.xml" stored within the document .odt file, and as you said this persists if the document is opened, edited and saved. In this graph I have been able to add multiple custom metadata items linked to each paragraph, using their unique ID inserted with the "ensureMetadataReference" method.
Thanks a lot for the help!
Code: Select all
XDocumentMetadataAccess metadataAccess = UnoRuntime.queryInterface(XDocumentMetadataAccess.class, xComp);
XURI metaTypeSequence = URI.createKnown(xContext, URIs.RDF_SEQ);
XURI metaTypeComment = URI.createKnown(xContext, URIs.RDFS_COMMENT);
XURI metaTypeLabel = URI.createKnown(xContext, URIs.RDFS_LABEL);
XURI[] metaTypes = new XURI[] {metaTypeSequence, metaTypeComment, metaTypeLabel};
XURI metaGraphName = metadataAccess.addMetadataFile("customMeta.xml", metaTypes);
XNamedGraph metaGraph = xRepo.getGraph(metaGraphName);
...
XMetadatable metadatable = UnoRuntime.queryInterface(XMetadatable.class, xTextElement);
metadatable.ensureMetadataReference();
XURI paraUri = UnoRuntime.queryInterface(XURI.class, xTextElement);
String paraId = Integer.toString(paraNum + 100);
XLiteral literal = Literal.create(xContext, paraId);
metaGraph.addStatement(paraUri, metaTypeSequence, literal);
literal = Literal.create(xContext, "This is a comment on Para Id " + paraId);
metaGraph.addStatement(paraUri, metaTypeComment, literal);
literal = Literal.create(xContext, "davide");
metaGraph.addStatement(paraUri, metaTypeLabel, literal);
LibreOffice 24.2 on Windows