I know that I have a repeated problem here in the forum but in my example I can´t find the solution.
I created a simple document (attached in the post)
I want to execute the find/replace text task.
I defined that my variables is marked between two pairs of '@@' (in this case called @@variable@@)
I googled to find the solutions. I think that I have the 'split text' problem. One of the solutions that I found to avoid the 'split text' problem is to programatically disable the RsIds and spell. I tried it but I have the same problem.
Now I tested with version 3.0 (but I started tested with older versions)
Many thanks in advance
- Code: Select all
private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement) {
obj = ((JAXBElement<?>) obj).getValue();
}
if (obj.getClass().equals(toSearch)) {
result.add(obj);
} else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
private static void replacePlaceholder(WordprocessingMLPackage template, String name, String placeholder ) {
List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class);
for (Object text : texts) {
Text textElement = (Text) text;
if (textElement.getValue().equals(placeholder)) {
textElement.setValue(name);
}
}
}
public static void main(String[] args) throws Exception {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new FileInputStream(new File("c:\\documento_template_simples.docx")));
WordprocessingMLPackage.FilterSettings filterSettings = new WordprocessingMLPackage.FilterSettings();
filterSettings.setRemoveProofErrors(true);
filterSettings.setRemoveContentControls(true);
filterSettings.setRemoveRsids(true);
wordMLPackage.filter(filterSettings);
replacePlaceholder(wordMLPackage, "text to replace", "@@variable@@");
wordMLPackage.save(new File("c:\\documento_final.docx"));
}
The part of document.xml that contains the variables is:
- Code: Select all
<w:p w:rsidR="00EE275D" w:rsidRDefault="000A40A3" w:rsidP="00EE275D"><w:pPr><w:pStyle w:val="SemEspaamento"/></w:pPr><w:r><w:t>@@</w:t></w:r><w:proofErr w:type="spellStart"/><w:r><w:t>varia</w:t></w:r><w:r w:rsidR="002E2992"><w:t>ble</w:t></w:r><w:proofErr w:type="spellEnd"/><w:r><w:t>@@</w:t></w:r></w:p><w:p w:rsidR="00EE275D" w:rsidRDefault="005D49F6" w:rsidP="00EE275D"><w:pPr><w:pStyle w:val="SemEspaamento"/></w:pPr><w:r><w:t>@@</w:t></w:r><w:r w:rsidR="00EE275D"><w:t>varia</w:t></w:r><w:r w:rsidR="002E2992"><w:t>ble</w:t></w:r><w:r w:rsidR="00EE275D"><w:t>@@</w:t></w:r></w:p><w:sectPr w:rsidR="00EE275D"><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1417" w:right="1701" w:bottom="1417" w:left="1701" w:header="708" w:footer="708" w:gutter="0"/><w:cols w:space="708"/><w:docGrid w:linePitch="360"/></w:sectPr>