1

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);
}
James
  • 41
  • 5
  • 1
    Maybe there are multiple sections in the document, not onle the one of the body? See https://stackoverflow.com/questions/50054304/how-to-set-page-number-for-different-section-in-word-by-poi/50056982#50056982 for an example – Axel Richter Sep 26 '18 at 05:54
  • As I recall, the *order* of the section properties is critical. As far as I can tell, this code is just appending a new one. If I look at the underlying Word Open XML of a test file in which I've specified page numbering to start at 5 the `` element is added directly after the `w:footer` element. You might try making sure that you do the same... – Cindy Meister Sep 26 '18 at 06:41

1 Answers1

1

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
}
James
  • 41
  • 5