Vito Karleone
Vito Karleone

Reputation: 385

Java Open\LibreOffice insert file\object in odt

Is there any way or example how to embed file\object in odt using Open\LibreOffice API for java ?

Or with some other API's or languages.

Upvotes: 0

Views: 676

Answers (1)

Kamlesh Samrit
Kamlesh Samrit

Reputation: 73

Here's a snippet of it in action:

    public static void main(String[] args) {
    try {
        OdfDocument odfDoc = OdfDocument.loadDocument(new File("/home/geertjan/test.ods"));
        OdfFileDom odfContent = odfDoc.getContentDom();
        XPath xpath = odfDoc.getXPath();
        DTMNodeList nodeList = (DTMNodeList) xpath.evaluate("//table:table-row/table:table-cell[1]", odfContent, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node cell = nodeList.item(i);
            if (!cell.getTextContent().isEmpty()) {
                System.out.println(cell.getTextContent());
            }
        }
    } catch (Exception ex) {
        //Handle...
    }
}

Let's assume that the 'test.ods' file above has this content: enter image description here

From the above, the code listing would print the following:

Cuthbert
Algernon
Wilbert

And, as a second example, here's me reading the first paragraph of an OpenOffice Text document:

public static void main(String[] args) {
    try {
        OdfDocument odfDoc = OdfDocument.loadDocument(new File("/home/geertjan/chapter2.odt"));
        OdfFileDom odfContent = odfDoc.getContentDom();
        XPath xpath = odfDoc.getXPath();
        OdfParagraphElement para = (OdfParagraphElement) xpath.evaluate("//text:p[1]", odfContent, XPathConstants.NODE);
        System.out.println(para.getFirstChild().getNodeValue());
    } catch (Exception ex) {
        //Handle...
    }
}

On my classpath I have "odfdom.jar" and "xerces-2.8.0.jar".

Upvotes: 1

Related Questions