使用 Java 将页码设置为从 Word 中的给定数字开始

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

我可以使用 this technique 将页码添加到 docx 文件,但我不知道如何让页码以特定数字开头(例如,我想要第一页说“5”)。

我试过使用 CTPageNumber,但以下内容没有向文档添加任何内容:

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);
}

修修补补一段时间后,我解决了这个问题:

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
}