I\'m tying to replace tokens in the header of docx file.I have handled the token replacement in paragraphs and tables but its not picking the header data. Im using apache po
I don't know if you have got the solution for this question. But, I've tried to replace tokens in document header and it worked for me.
public XWPFDocument setHeader(XWPFDocument document, String token, String textToReplace){
XWPFHeaderFooterPolicy policy= document.getHeaderFooterPolicy();
XWPFHeader header = policy.getHeader(0);
replaceInParagraphs(header.getParagraphs(), token, textToReplace);
return document;
}
private void replaceInParagraphs(List paragraphs, String placeHolder, String replaceText){
for (XWPFParagraph xwpfParagraph : paragraphs) {
List runs = xwpfParagraph.getRuns();
for (XWPFRun run : runs) {
String runText = run.getText(run.getTextPosition());
if(placeHolder !="" && !placeHolder.isEmpty()){
if(runText != null &&
Pattern.compile(placeHolder, Pattern.CASE_INSENSITIVE).matcher(runText).find()){
runText = replaceText;
}
}
run.setText(runText, 0);
}
}
}
Hope this helps. :)