Search code examples
javadocx4j

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:

Before
original format in template

After
format after replacement

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?


Solution

  • Like Jason pointed out in the comments, my code doesn't change the format!
    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!