(The open source Java library for manipulating docx files)
by sledwich » Fri Mar 30, 2012 1:29 am
Hi I am really interested in using the new FieldLocator class and its associated Field class level functionality. Is there any instructions or samples I can use to see how it works?
Thanks
-
sledwich
-
- Posts: 8
- Joined: Thu Apr 07, 2011 1:04 am
by jason » Fri Mar 30, 2012 8:45 am
You can see it in use in MailMerger:
Using java Syntax Highlighting
// to facilitate cloning, wrap the list in a body
Body shell
= Context.
getWmlObjectFactory().
createBody();
shell.
getContent().
addAll(contentList.
getContent());
Body shellClone
= (Body
)XmlUtils.
deepCopy(shell
);
// find fields
FieldLocator fl
= new FieldLocator
();
new TraversalUtil
(shellClone, fl
);
log.
info("Found " + fl.
getStarts().
size() + " fields ");
// canonicalise and setup fieldRefs
List
<FieldRef
> fieldRefs
= new ArrayList
<FieldRef
>();
for( P p
: fl.
getStarts() ) {
int index
= ((ContentAccessor
)p.
getParent()).
getContent().
indexOf(p
);
P newP
= FieldsPreprocessor.
canonicalise(p, fieldRefs
);
System.
out.
println("NewP length: " + newP.
getContent().
size() );
((ContentAccessor
)p.
getParent()).
getContent().
set(index, newP
);
}
// Populate
for (FieldRef fr
: fieldRefs
) {
String instr
= fr.
getInstr();
if ( isMergeField
(instr
) ) {
// eg <w:instrText xml:space="preserve"> MERGEFIELD Kundenstrasse \* MERGEFORMAT </w:instrText>
String tmp
= instr.
substring( instr.
indexOf("MERGEFIELD") + 10
);
tmp
= tmp.
trim();
String key
= tmp.
substring(0, tmp.
indexOf(" ")) ;
log.
info("Key: '" + key
+ "'");
String val
= datamap.
get( new DataFieldName
(key
));
if (val
==null) {
log.
warn("Couldn't find value for key: '" + key
+ "'");
} else {
fr.
setResult(val
);
}
// If doing an actual mail merge, the begin-separate run is removed, as is the end run
fr.
getParent().
getContent().
remove(fr.
getBeginRun());
fr.
getParent().
getContent().
remove(fr.
getEndRun());
// System.out.println(XmlUtils.marshaltoString(
// fr.getParent(), true, true));
}
}
Parsed in 0.018 seconds, using
GeSHi 1.0.8.4
-
jason
-
- Posts: 4030
- Joined: Wed Mar 19, 2008 11:47 pm
Return to docx4j
Who is online
Users browsing this forum: Bing [Bot], Google [Bot] and 85 guests