docx4j replace variable with html

﹥>﹥吖頭↗ 提交于 2020-01-04 14:08:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!