3

I would like to create a header and footer on a docx document (a new one and not existing one) with XWPF jars (apache poi).

When I use XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy(); policy is null, so I would know how to create it in a new document.

CustomXWPFDocument document = new CustomXWPFDocument();
XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy();
XWPFHeader head = policy.createHeader(policy.DEFAULT);
head.getListParagraph().get(0).createRun().setText("Hello Header World!");
CTP ctP1 = CTP.Factory.newInstance();
CTR ctR1 = ctP1.addNewR();
CTText t = ctR1.addNewT();
t.setStringValue("Paragraph in header");
XWPFParagraph p1 = new XWPFParagraph(ctP1, document);
XWPFParagraph[] pars = new XWPFParagraph[1];
pars[0] = p1;
policy.createHeader(policy.FIRST, pars);
whoan
  • 8,143
  • 4
  • 39
  • 48

3 Answers3

1

You must add a section property to the XWPFDocument doc if not already present by using following code

CTBody body = doc.getDocument().getBody();
CTSectPr sectPr = body.isSetSectPr()? body.getSectPr() : body.addNewSectPr();
bbhar
  • 599
  • 5
  • 8
1
public static void setFooter(XWPFDocument document, String footerText) {
    CTP ctpFooter = CTP.Factory.newInstance();
    ctpFooter.addNewR().addNewT();

    XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);
    XWPFRun footerRun = createFormattedRun(footerParagraph);
    footerRun.setFontSize(6);
    footerRun.setText(footerText);
    XWPFParagraph[] parsFooter = new XWPFParagraph[1];
    parsFooter[0] = footerParagraph;

    CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
    XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);
    policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
}
Meindert
  • 384
  • 2
  • 9
0

I had the same problem but didn't find any solution. In this case I created template docx file with header and footer and than change them. This practice I found in Apache mail archives.

njjnex
  • 1,490
  • 13
  • 23
  • thank you, i saw it befor but doesn't helping for my application. my document is generated and don't have tamplate, but i can use one template only for the recuperation of the header and footer and inser it in the generated document... and don't know how to do – Riyadh BOUREZZANE Nov 26 '14 at 09:27