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?