java - 添加页脚 Word apache poi java

标签 java ms-word apache-poi footer

我想将页脚添加到apache poi库生成的word文档中,问题是我的方法总是只在最后一页添加页脚文本,我错过了什么吗?谢谢, 这是我的方法

 private void addWordFooter(XWPFDocument document, CTBody body, String clientDate,
        String graphName, long TabWidth) throws IOException, InvalidFormatException {

    CTSectPr sectPr = body.getSectPr();
    if(sectPr==null)
    {
        sectPr = body.addNewSectPr();
    }


    CTP footerCtp = CTP.Factory.newInstance();
    CTR footerCtr = footerCtp.addNewR();
    XWPFParagraph footerCopyrightParagraph = new XWPFParagraph(footerCtp, document);
    document.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
    XWPFRun run = footerCopyrightParagraph.getRun(footerCtr);
    run.setText(graphName);
    run.addTab();
    run.setText(clientDate);
    setTabStop(footerCtp, STTabJc.Enum.forString("right"), BigInteger.valueOf(TabWidth));

    XWPFParagraph[] footerParagraphs = { footerCopyrightParagraph };

    XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
    headerFooterPolicy.createFooter(STHdrFtr.DEFAULT, footerParagraphs);
}

setTabStop 方法:

private  void setTabStop(CTP oCTP, STTabJc.Enum oSTTabJc, BigInteger oPos) {
    CTPPr oPPr = oCTP.getPPr();
    if (oPPr == null) {
        oPPr = oCTP.addNewPPr();
    }

    CTTabs oTabs = oPPr.getTabs();
    if (oTabs == null) {
        oTabs = oPPr.addNewTabs();
    }

    CTTabStop oTabStop = oTabs.addNewTab();
    oTabStop.setVal(oSTTabJc);
    oTabStop.setPos(oPos);
}

最佳答案

试试这个:

private void addWordFooter(XWPFDocument document, String text) throws IOException {
    CTP ctp = CTP.Factory.newInstance();
    CTText t = ctp.addNewR().addNewT();
    t.setStringValue(text);
    XWPFParagraph pars[] = new XWPFParagraph[1];
    pars[0] = new XWPFParagraph(ctp, document);

    XWPFHeaderFooterPolicy hfp = document.createHeaderFooterPolicy();
    hfp.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);
    //hfp.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);
}

关于java - 添加页脚 Word apache poi java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40607922/

相关文章:

java - 如何在 JodConverter 中读取 doc 或 pdf 中的文本

java - 如何调用dll

java - 什么时候需要对象类的引用?

ms-word - 为MS Word推荐一个程序员词典

c# - 验证 Word 2007 模板文件

java - Apache POI hsmf 对 getMesssageDate 返回 null

java - 使用 ChronicleMap 和ExternalMapQueryContext 进行对象分配

java - 波兰/斯拉夫语言名词变格算法

c# - 字互操作 C# : Insert new page using existing page

java - Apache POI 3.7 OutOfMemoryError : Java heap space when writing to large no of rows to xlsx files