How to create a header/footer in new docx document?

2.4k views Asked by At

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

There are 3 answers

1
njjnex On

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.

0
Meindert On
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);
}
0
bbhar On

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