Skip to content

Instantly share code, notes, and snippets.

@epochcoder
Created August 5, 2014 11:04
Show Gist options
  • Save epochcoder/478a72a4b59a43995373 to your computer and use it in GitHub Desktop.
Save epochcoder/478a72a4b59a43995373 to your computer and use it in GitHub Desktop.
docx4j-html-replacement
/**
* Traverse a list of JAXB objects (eg. document.xml's document/body children), retrieve the w:p elements
* and run replacements on them according to the supplied map of identifiers and data
* @param mainPart the main document part
* @param replacements a map with an identifier as key and a list of paragraphs to replace the found one with
*/
private static void runReplacements(final MainDocumentPart mainPart, final Map<String, List<Object>> replacements) {
Preconditions.checkNotNull(mainPart, "the supplied main doc part may not be null!");
Preconditions.checkNotNull(replacements, "replacements may not be null!");
// look for all P elements in the specified object
final List<P> paragraphs = Lists.newArrayList();
new TraversalUtil(mainPart, new TraversalUtil.CallbackImpl() {
@Override
public List<Object> apply(Object o) {
if (o instanceof P) {
paragraphs.add((P) o);
}
return null;
}
});
// run through all found paragraphs to located identifiers
for (final P paragraph : paragraphs) {
// check if this is one of our identifiers
final StringWriter paragraphText = new StringWriter();
try {
TextUtils.extractText(paragraph, paragraphText);
} catch (Exception ex) {
LOG.warning(Logger.EVENT_FAILURE, "failure while extracting text from w:p", ex);
}
final String identifier = paragraphText.toString();
if (identifier != null && replacements.containsKey(identifier)) {
final List<Object> listToModify;
if (paragraph.getParent() instanceof Tc) {
// paragraph located in table-cell
final Tc parent = (Tc) paragraph.getParent();
listToModify = parent.getContent();
} else {
// paragraph located in main document part
listToModify = mainPart.getContent();
}
if (listToModify != null) {
final int index = listToModify.indexOf(paragraph);
Preconditions.checkState(index > -1, "could not located the paragraph in the specified list!");
// remove the paragraph from it's current index
listToModify.remove(index);
// add the converted HTML paragraphs
listToModify.addAll(index, replacements.get(identifier));
}
}
}
}
@horelvis
Copy link

Hi Bro!
Thank you for shared this code! your saved my life! ๐Ÿ˜…

@epochcoder
Copy link
Author

Glad it helped ๐Ÿ˜Š

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment