1
votes

I want to add footer to my word document generated by apache poi library, the problem that my method always add the the footer text only in the last page, m i missing something ? Thanks, this bellow my method

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

The setTabStop method:

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

2 Answers

1
votes

Try this:

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

After some testing I think you are calling this function only on the last body.

Remove this argument CTBody body from addWordFooter().

And add this line to your function

CTSectPr sectPr = d.getDocument().getBody().addNewSectPr();

It will apply footer to your entire .docx.

Contrary to your issue, I'm trying to add footer only to the last page, and by passing a particular CTBody body I could replicate your issue.