首页 > 解决方案 > 在 Word with Java 中将页码设置为从给定数字开始

问题描述

我可以使用这种技术将页码添加到 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);
}

标签: javams-wordapache-poifooterpage-numbering

解决方案


经过一段时间的修补,我能够通过以下方式解决它:

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
}

推荐阅读