我得到了这个示例代码,用文本替换变量,它完美无缺。
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"));
但现在我必须用html替换变量。我试过这样的事。但是因为它不起作用
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"));
有没有办法实现这个目标?
答案 0 :(得分:2)
变量替换的东西都是关于在WordML中交换简单值,它不适用于HTML。
您需要以正确的方式将(X)HTML导入Word文档。在最新版本的docx4j中,这是通过ImportXHTML子项目完成的:https://github.com/plutext/docx4j-ImportXHTML(在早期版本中,XHTML导入代码是主docx4j项目的一部分)。
本质上,代码采用格式良好的XHTML,将其解析为WordML构造(即文本元素,运行,段落等),然后您可以将生成的对象集合插入到Word文件中。一个例子:
// 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));