简体   繁体   English

Docx4j-替换占位符会破坏格式

[英]Docx4j - replacing placeholder destroys format

When trying to replace my placeholding text in a word template with the docx4j framework the formatting is always lost: 当尝试使用docx4j框架将我的占位符文本替换为word模板时,格式总是丢失:

Before 之前
模板中的原始格式

After
更换后的格式

I tried to simplify the code to the core of what I'm doing here: 我试图将代码简化为我在这里所做的工作的核心:

private void replacePlaceholder(WordprocessingMLPackage template,
                                String name,
                                String placeholder) {
    List<Object> texts =
        doc.getAllElementFromObject(template.getMainDocumentPart(), Text.class);
    for (Object text : texts) {
        Text textElement = (Text) text;

        if (textElement != null
                && textElement.getValue() != null
                && placeholder != null
                && textElement.getValue().equals(placeholder)) {
            textElement.setValue(name);
        }
    }
}

WordprocessingMLPackage wp = 
    WordprocessingMLPackage.load(context.getResourceAsStream("/template.docx"));
replacePlaceholder(wp, "Apr. 2007 - Dez. 2012", "tempDatum");

Anyone an idea what I should do in order to keep my original formatting? 有人知道我应该怎么做才能保持原始格式吗?

Like Jason pointed out in the comments, my code doesn't change the format! 就像Jason在评论中指出的那样,我的代码不会更改格式!
But since it always jumped back to the standard format I just edited that standard format in my template, saved it and then it worked! 但是由于它总是跳回到标准格式,所以我只是在模板中编辑了该标准格式,将其保存后就可以使用了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM