【问题标题】:Add page number with offset to docx using Apache POI使用 Apache POI 将带有偏移量的页码添加到 docx
【发布时间】:2023-03-12 03:45:01
【问题描述】:

我正在使用 Apache POI 生成 docx 文档。使用以下代码,我可以将自动生成的数字添加到页脚:

private void createDocFooter(XWPFDocument docx) {

    XWPFFooter footer = docx.createFooter(HeaderFooterType.DEFAULT);

    XWPFParagraph paragraph = footer.getParagraphArray(0);
    if (paragraph == null) {
        paragraph = footer.createParagraph();
    }

    paragraph.setAlignment(ParagraphAlignment.CENTER);

    paragraph.getCTP().addNewFldSimple().setInstr("PAGE");
}

问题是它总是从 1 开始。如何为该指令提供偏移量以从例如开始编号? 5?

【问题讨论】:

    标签: java apache-poi docx


    【解决方案1】:

    页码起始值在部分属性中设置。如果只有一个部分,则这是文档正文的部分属性。

    Apache POI 不提供任何方法来设置其高级类中的部分属性。所以需要使用ooxml 的底层低级类。

    以下方法应该可以满足您的要求。它将页码类型的开始设置为start中给出的页。

     private void setPageNumberStart(XWPFDocument doc, java.math.BigInteger start) {
      if(doc.getDocument().getBody().isSetSectPr()) {
       if (doc.getDocument().getBody().getSectPr().isSetPgNumType()) {
        doc.getDocument().getBody().getSectPr().getPgNumType().setStart(start);
       } else {
        doc.getDocument().getBody().getSectPr().addNewPgNumType().setStart(start);
       }
      } else {
       doc.getDocument().getBody().addNewSectPr().addNewPgNumType().setStart(start);
      }  
     }
    

    当这样调用时:

    ...
    XWPFDocument doc = ...
    ...
    setPageNumberStart(doc, java.math.BigInteger.valueOf(5));
    ...
    

    它将页码类型的开始设置为第 5 页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 2020-08-18
      • 1970-01-01
      • 2016-10-29
      相关资源
      最近更新 更多