问题
i got this sample code to replace variables with text and it works perfect.
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("c:/template.docx"));
VariablePrepare.prepare(wordMLPackage);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("firstname", "Name"); //${firstname}
mappings.put("lastname", "Name"); //${lastname}
documentPart.variableReplace(mappings);
wordMLPackage.save(new java.io.File("c:/replace.docx"));
but now i have to replace the variables with html. I tried something like this. but of cause it does not work
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("c:/template.docx"));
VariablePrepare.prepare(wordMLPackage);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
String html = "<html><head><title>Import me</title></head><body><p style='color:#ff0000;'>Hello World!</p></body></html>";
AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/hw.html"));
afiPart.setBinaryData(html.toString().getBytes());
afiPart.setContentType(new ContentType("text/html"));
Relationship altChunkRel = documentPart.addTargetPart(afiPart);
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId());
HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("firstname", ac.toString()); //${firstname}
mappings.put("lastname", "Name"); //${lastname}
documentPart.variableReplace(mappings);
wordMLPackage.save(new java.io.File("c:/replace.docx"));
Is there any way to achieve this?
回答1:
The variable replacement stuff is all about swapping out simple values in WordML, it won't work for HTML.
You need to import (X)HTML into your Word document the correct way. In the latest version of docx4j, this is done via the ImportXHTML sub-project: https://github.com/plutext/docx4j-ImportXHTML (in earlier versions, the XHTML import code is part of the main docx4j project).
Essentially the code takes well-formed XHTML, parses it into WordML constructs (i.e. text elements, runs, paragraphs and so on), and then you can insert the resulting collection of objects into your Word file. An example:
// Where xhtml = String representing well-formed XHTML to insert
// Where pkg = your WordProcessingMLPackage instance
XHTMLImporterImpl importer = new XHTMLImporterImpl(pkg);
pkg.getMainDocumentPart().getContent().addAll(importer.convert(xhtml, null));
来源:https://stackoverflow.com/questions/24628367/docx4j-replace-variable-with-html