I'm creating a small program to create a batch of documents. In the footer of each created document, I tried to reflect the serial number of the current page and the total number of pages in the document, that is, to provide a line like: “Page 1 of 3.” However, it is not possible to correctly reflect the total number of pages in one document. The footer appears to display the total number of pages for the entire document package.
Here is part of my code:
XWPFHeaderFooterPolicy headerFooterPolicy = firstDocument.getHeaderFooterPolicy();
if (headerFooterPolicy == null)
headerFooterPolicy = firstDocument.createHeaderFooterPolicy();
XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
XWPFParagraph parafooter = footer.createParagraph();
parafooter.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun runfooter = parafooter.createRun();
runfooter.setText("First line");
runfooter.setFontFamily("Times New Roman");
XWPFParagraph parafooter1 = footer.createParagraph();
parafooter1.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun runfooter1 = parafooter1.createRun();
runfooter1.setText("page no. ");
runfooter1.getCTR().addNewPgNum();
runfooter1=parafooter1.createRun();
runfooter1.setText(" of " + firstDocument.getBodyElements().size());
runfooter1.setFontFamily("Times New Roman");
firstDocument.write(new FileOutputStream(new File(fileString + "\\FirstFile.doc")));
firstDocument.close();
This is the result that appears in the footer:
First line
page no. 1 of 41
I tried using different functions, but did not achieve a positive result.