Docx4j - Replacing Word merge field with HTML content

1.1k Views Asked by At

I am trying to replace a Word merge field "test" with an HTML content :

String myText = "<html><body><h1>Hello</h1></body></html>"; 

using Docx4j.

  String myText = "<html><body><h1>Hello</h1></body></html>";
  try {
        WordprocessingMLPackage docxOut =
                WordprocessingMLPackage.load(new java.io.File("/tmp/template.docx"));
        Map<DataFieldName, String> data = new HashMap<>();
        data.put(new DataFieldName("test"), myText);
        org.docx4j.model.fields.merge.MailMerger.performMerge(docxOut, data, true);
        docxOut.save(new java.io.File("/tmp/newTemplate.docx"));
    } catch (Docx4JException e) {
        LOGGER.error(e.getMessage());
    }

As a result, I have an output (newTemplate.docx) with my merge field replaced by

"<html><body><h1>Hello</h1></body></html>" 

without being interpreted as HTML. I tried adding :

docxOut.getContentTypeManager().addDefaultContentType("html", "text/html");

but it still didn't work. I am not even sure if interpreting HTML while replacing a Word merge field can be done using Docx4j or if I'm missing something.

Any help would be welcome.

1

There are 1 best solutions below

7
On

You can use the OpenDoPE approach to bind a content control to a Custom XML element which contains escaped XHTML.