首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中编程修改Libre Office odt文档?

如何在java中编程修改Libre Office odt文档?
EN

Stack Overflow用户
提问于 2022-05-27 12:50:44
回答 1查看 245关注 0票数 -4

代码语言:javascript
复制
package army;

import org.apache.commons.io.FileUtils;
import org.odftoolkit.odfdom.doc.OdfTextDocument;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

public class LibreOfficeWriter2 {

    public static void main(String[] args) throws Exception {
        OdfTextDocument odt = OdfTextDocument.loadDocument("MyFilename.odt");
        InputStream contentStream = odt.getContentStream();

        String text = new BufferedReader(
                new InputStreamReader(contentStream, StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(contentStream, StandardCharsets.UTF_8));
        setText(text);
        contentStream.close();
        odt.close();
        bufferedReader.close();
    }

    public static void setText(String text) {
        try {
            FileUtils.writeByteArrayToFile(new File("result.odt"), text.replace("result", "***").getBytes());
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

最后,我提取了归档文件,处理和编辑了xml,但是我没有把它打包回去。有人知道怎么做吗?在这里输入图像描述

EN

回答 1

Stack Overflow用户

发布于 2022-05-27 14:46:27

ODF允许您使用OpenOffice/LibreOffice文档(带有扩展OpenDocument的.odt文本)及其以压缩XML格式存储的文本内容

ODFDOM允许编辑而不需要操作XML。

Java允许您使用抽象层OpenOffice文档对象模型(DOM)直接处理特定的XML结构。

对于修改文本,您可能对文本内容的元素感兴趣,例如,标题的<text:h>或段落的<text:p>。这些XML元素在OpenOffic中分别被建模为类TextHElementTextPElement

参见ODFDOM - OpenDocument API的快速启动示例

代码语言:javascript
复制
// Create a text document from a standard template
// (empty documents within the JAR)
OdfTextDocument odt = OdfTextDocument.newTextDocument();
// Append text to the end of the document.
odt.addText("This is my very first ODF test");
// Save document
odt.save("MyFilename.odt");

打开

要么使用newTextDocument()创建一个新的,要么使用loadDocument(File)方法加载现有的。

修改

使用打开文档的文档对象模型(DOM) (例如odt)来添加、删除或修改元素。DOM包含具有不同节点或元素的树结构(每个节点或元素代表特定的XML元素)。

例如,要获得第一段文本并替换它:

代码语言:javascript
复制
// get the root element inside ODF XML
OdfElement root = odt.getContentRoot();
// count the child elements of root
int childrenCount = root.countChildComponents(true);
System.out.println(childrenCount);

// get a paragraph and its text, e.g. the first
OdfElement firstParagraph = OdfElement.findFirstChildNode(TextPElement.class, root);
System.out.println(firstParagraph.getTextContent());

// modify the text
firstParagraph.setTextContent("Hello World!");

用于处理DOM元素的方法:

保存

使用的save方法是OdfTextDocument的一个特殊方法,它直接接受带有文件名的字符串。

而且,从抽象OpenDocument继承的任何文档都有一个save(File)方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72405729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档