0

I tried following code to add footer in my document but it is not working fine.

  CTP ctp = CTP.Factory.newInstance();
    CTR ctr = ctp.addNewR();
    CTRPr rpr = ctr.addNewRPr();
    CTText textt = ctr.addNewT();
    textt.setStringValue( " Page 1" );
    XWPFParagraph codePara = new XWPFParagraph( ctp, document );
    XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
    newparagraphs[0] = codePara;
    CTSectPr sectPr1 = document.getDocument().getBody().addNewSectPr();
    XWPFHeaderFooterPolicy headerFooterPolicy = new  XWPFHeaderFooterPolicy( document,sectPr1 );

headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );

I am using following jars to generate my document. Please help...

  1. poi-3.10-FINAL-20140208.jar
  2. poi-ooxml-3.10-FINAL-20140208.jar
  3. poi-ooxml-schemas-3.10-FINAL-20140208.jar
  4. poi-scratchpad-3.10-FINAL-20140208
  • What do you mean by "not working fine"? Works partly? Gives an error? Shows up wrong? Also, there's no code shown saving the file, could it be as simple as that? – Gagravarr Oct 17 '14 at 15:55
  • Could you please help to complete the code? Please tell me how to save this to file? – Renjith Sharma Oct 19 '14 at 06:52
  • To save the file, it's the same for whatever format you use - just call [write(OutputStream)](https://poi.apache.org/apidocs/org/apache/poi/POIXMLDocument.html#write%28java.io.OutputStream%29) – Gagravarr Oct 19 '14 at 09:10
  • Thank you Gagravarr for your help. It worked. – Renjith Sharma Oct 21 '14 at 03:38

2 Answers2

0

Promoting a comment to an answer...

The problem is not with your header / footer code. The code in your question looks fine for doing what you want. In case you do want to do a bit more though, the best reference that springs to mind is the unit tests for headers and footers in Apache POI, which cover more use cases

What your code doesn't do is write the file out after you have made your changes!

You just need to add in a call to write(OutputStream) at the end of your code, and you'll be done. Something like

FileOutputStream out = new FileOutputStream("WithHeader.docx");
document.write(out);
out.close();
Gagravarr
  • 47,320
  • 10
  • 111
  • 156
-1

Adding footer to ms word using POI api

CTP ctp = CTP.Factory.newInstance();
        CTR ctr = ctp.addNewR();
        CTRPr rpr = ctr.addNewRPr();
        CTText textt = ctr.addNewT();
        textt.setStringValue( " Page 1" );
        XWPFParagraph codePara = new XWPFParagraph( ctp, document );
        XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
        newparagraphs[0] = codePara;
        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy headerFooterPolicy = new  XWPFHeaderFooterPolicy( document, sectPr );
        headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );
Community
  • 1
  • 1
Bhupendra
  • 1
  • 1