简体   繁体   中英

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 (eg, 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);
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM