When using document variables in word, they get saved as a sort of key value pair in settings.xml.
In the document itself, (if inserted), they appear as either the key-string or value-string. With docx4j I can easily traverse settings.xml and replace docVar values. The Problem is, that in document.xml, the original value is still saved, until someone manually opens the .docx in word and refreshes the field with f9. Is there a way to refresh the field in document.xml with docx4j so that I dont have to worry about the old value still existing? Here is my code if its any help:
- Code: Select all
public String changeVars (String filePath, Properties prop) {
if(filePath == null || prop == null) { return null; }
try {
WordprocessingMLPackage wmlpack = WordprocessingMLPackage.load(new File(filePath));
System.out.println("File geladen");
DocumentSettingsPart settingsPart = wmlpack.getMainDocumentPart().getDocumentSettingsPart();
String xpath= "//w:docVar";
List<Object> list = settingsPart.getJAXBNodesViaXPath(xpath, false);
if(list.isEmpty()) { System.out.println("Liste Leer! Keine docVars vorhanden!"); }
else {
for (Object object : list) {
org.docx4j.wml.CTDocVar docVar = (org.docx4j.wml.CTDocVar)object;
String newVal = prop.getProperty(docVar.getName());
if(newVal != null) {
docVar.setVal(newVal);
System.out.println("docVar Value ersetzt.");
}
}
}
Random rnd = new Random();
int number = rnd.nextInt(999999);
String[] nameParts = filePath.split("(?=\\.)");
File newFile = new File(String.format("%s_%06d%s", nameParts[0], number, nameParts[1]));
FieldUpdater updater = new FieldUpdater(wmlpack);
updater.update(true);
Docx4J.save(wmlpack, newFile);
System.out.println("Neues docx erstellt!");
return newFile.toString();
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
I used the FieldUpdater thinking it would solve my problem, but it didnt so just ignore it along with the sys out prints.
Any help would be immensely appreciated!!!
![Very Happy :D](https://www.docx4java.org/forums/images/smilies/icon_e_biggrin.gif)