I use some suggestion over this site but I found NullPointerException
at this line:
policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
I use some suggestion over this site but I found NullPointerException
at this line:
policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
This is how I create a footer in POI 3.14. There might need to be some changes for 3.15 onward though.
public static XWPFFooter createFooter(XWPFDocument doc) {
XWPFFooter ftr;
XWPFHeaderFooterPolicy hfp = doc.createHeaderFooterPolicy();
try {
ftr = hfp.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
} catch (IOException e) {
return null;
}
ftr.removeParagraph(0);
return ftr;
}
Note the removeParagraph(0)
at the end there. POI currently creates headers and footers with a blank paragraph (or filled with something if you do it right), but I like to create the footer, and add paragraphs later. It simplifies my code to not have to handle the first paragraph differently than the rest. If you are ok with the empty paragraph being there when you first create your footer, then you can remove that line, but the empty paragraph is not generated by POI in later versions. Not sure when that change was made, but I think some time around 3.16.
Still for 3.14: to add a page number to the footer you need to drop into the CT classes to insert a field. I do that with a new method. Note: CT classes are only there so you can get to functionality that is not implemented in POI, you shouldn't rely on them for implemented features.
public static XWPFRun createSimpleField(XWPFParagraph p, String instr, String dft) {
CTP ctp = p.getCTP();
CTSimpleField field = ctp.addNewFldSimple();
field.setInstr(instr);
CTR r = field.addNewR();
CTText t = r.addNewT();
t.setStringValue(dft);
return new XWPFFieldRun(field, r, p);
}
Putting it all together now and assuming that these two static methods are contained in MyUtilClass
, we can add page numbers to a footer like this:
XWPFFooter ftr = MyUtilClass.createFooter(doc);
XWPFParagraph p = ftr.createParagraph();
XWPFRun r = p.createRun();
r.setText("Page ");
r = MyUtilClass.createSimpleField(p, "PAGE", "1");
r = p.createRun();
r.setText(" of ");
r = MyUtilClass.createSimpleField(p, "NUMPAGES", "1");