I need to replace content controls with text in word document using docx4j
I refer this link ,I'm not able to understand how to get .xml file from .docx file Does anyone know where I can find code examples of this?
I need to replace content controls with text in word document using docx4j
I refer this link ,I'm not able to understand how to get .xml file from .docx file Does anyone know where I can find code examples of this?
private static void replaceTextValue(WordprocessingMLPackage template, String name, String placeholder)
throws Exception {
List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), SdtBlock.class);
// System.out.println(template.getMainDocumentPart().getXML());
for (Object text : texts) {
SdtBlock textElement = (SdtBlock) text;
List<Object> cList = textElement.getSdtContent().getContent();
ClassFinder finder = new ClassFinder(Text.class);
new TraversalUtil(cList, finder);
for (Object o : finder.results) {
Object o2 = XmlUtils.unwrap(o);
if (o2 instanceof org.docx4j.wml.Text) {
String CTagVal = ((org.docx4j.wml.Text) o2).getValue();
if (CTagVal.equalsIgnoreCase(placeholder)) {
org.docx4j.wml.Text txt = (org.docx4j.wml.Text) o2;
txt.setValue(name);
}
} else {
System.out.println(XmlUtils.marshaltoString(o, true, true));
}
}
}
}
this method replace the text inside the control
I'm working through content controls in docx4j myself. If you just want to view the xml of a docx file, you can replace the .docx file extention with .zip which is essentially what it is. Then go into the zip file and you will find the underlying xml. I believe there are apps that will allow you to edit and save docx xml, but havent looked into that much.
If you want to insert a content control in a word template, you first need to turn on the developer tab. see https://msdn.microsoft.com/en-us/library/bb608625.aspx . This will add a Controls section under the developer tab. see: https://gregmaxey.com/word_tip_pages/content_controls.html
I haven't found a good example of doing the actual variable replacement with the controls only with XmlUtils.unmarshallFromTemplate(xmlString , mappings) which seems to have a lot of quarks. If you work that part out, please post.