java - 在 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);
}
解决方案
经过一段时间的修补,我能够通过以下方式解决它:
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
}
推荐阅读
- java - 按模块分组的项目的 Maven 肯定测试结果
- excel - VBA:右键单击用户表单
- hadoop - 带有 Kerberos 和 OpenLDAP 的 HDFS -“不允许 test@HDFS.COM 模拟测试”
- python-3.x - 打印 discord.Interaction 抛出错误 discord.py
- javascript - 如何在 React 中跨映射数组跟踪状态?
- flutter - 从 Firestore 按类别过滤 Flutter listview.builder
- automation - 如何维护特征文件中的补丁细节,易于维护
- python - Flask通过pydub输入mp3文件
- c# - UPDATE 语句与 asp.net mvc 中的 FOREIGN KEY 约束冲突
- ruby-on-rails - 如何将对控制器方法的访问限制为仅经过身份验证的用户?