first of all thanks to the developers. Docx4j is getting a great and easy tool to work with OpenXML.
I am trying to replace some text fields and am using your demo:
- Code: Select all
public static void main(String[] args) {
File f = new File("test.docx");
WordprocessingMLPackage wd;
try {
// 1. Load the Package
wd = WordprocessingMLPackage.load(f);
// 2. Fetch the document part
MainDocumentPart docPart = wd.getMainDocumentPart();
org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document)docPart.getJaxbElement();
Body body = wmlDocumentEl.getBody();
List <Object> bodyChildren = body.getEGBlockLevelElts();
walkJAXBElements(bodyChildren);
wd.save(new File("test_out.docx"));
} catch (Docx4JException e) {
e.printStackTrace();
}
}
/**
* Iterates through all body objects of the word document.
* @param bodyChildren
*/
static void walkJAXBElements(List <Object> bodyChildren){
for (Object o : bodyChildren ) {
if (o instanceof org.docx4j.wml.P) {
walkList( ((org.docx4j.wml.P)o).getParagraphContent());
}
}
}
/**
* Iterates through all child elements to find text fields.
* @param children
*/
@SuppressWarnings("unchecked")
static void walkList(List children){
for (Object o : children ) {
if ( o instanceof javax.xml.bind.JAXBElement) {
if ( ((JAXBElement)o).getDeclaredType().getName().equals("org.docx4j.wml.Text") ) {
org.docx4j.wml.Text t = (org.docx4j.wml.Text)((JAXBElement)o).getValue();
if(t.getValue().equals("[Name]")) {
t.setValue("Arnold");
}
}
} else if ( o instanceof org.docx4j.wml.R) {
org.docx4j.wml.R run = (org.docx4j.wml.R)o;
walkList(run.getRunContent());
}
}
}
In the example above, every Textfield which has [Name] as Value will be replaced. This example works only on documents without tables.
Does anybody know who I can get into tables to find Text-Object within them?