Search code examples
javams-wordapache-poifooterpage-numbering

Set page numbers to start at a given number in Word with Java


I'm able to add page numbers to a docx file with this technique, but I don't know how to get the page numbers to start with a particular number (e.g., I want the first page to say "5").

I've tried using CTPageNumber, but the following didn't add anything to the document:

static void addPageNumbers(XWPFDocument doc, int startingNum) {
  CTSectPr sectPr = doc.getDocument().getBody().isSetSectPr() ? doc.getDocument().getBody().getSectPr()
    : doc.getDocument().getBody().addNewSectPr();
  CTPageNumber pgNum = sectPr.isSetPgNumType() ? sectPr.getPgNumType() : sectPr.addNewPgNumType();
  pgNum.setStart(BigInteger.valueOf(startingNum));
  pgNum.setFmt(STNumberFormat.DECIMAL);
}

Solution

  • After tinkering for awhile, I was able to solve it with:

    static void addPageNumbers(XWPFDocument doc, long startingNum) {
      CTBody body = document.getDocument().getBody();
      CTSectPr sectPr = body.isSetSectPr() ? body.getSectPr() : body.addNewSectPr();
      CTPageNumber pgNum = sectPr.isSetPgNumType() ? sectPr.getPgNumType() : sectPr.addNewPgNumType();
      pgNum.setStart(BigInteger.valueOf(startingNum));
    
      CTP ctp = CTP.Factory.newInstance();
      ctp.addNewR().addNewPgNum(); // Not sure why this is necessary, but it is.
    
      XWPFParagraph footerParagraph = new XWPFParagraph(ctp, document);
      footerParagraph.setAlignment(ParagraphAlignment.CENTER); // position of number
      XWPFParagraph[] paragraphs = { footerParagraph };
    
      XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
      headerFooterPolicy.createFooter(STHdrFtr.FIRST, paragraphs);
      headerFooterPolicy.createFooter(STHdrFtr.DEFAULT, paragraphs); // DEFAULT doesn't include the first page
    }