POI enable different header/footer for the first page in word docx file Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of POI enable different header/footer for the first page in word docx file without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m generating a docx file using Apache POI 3.13 and I stuck with headers/footers for first page. I create XMPFParagraph[] without any problem. Next I create headers and footers like this (I’ve tried in different oreder):

policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, defaultHeader);
policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, defaultFooter);
policy.createHeader(XWPFHeaderFooterPolicy.FIRST, firstHeader);
policy.createFooter(XWPFHeaderFooterPolicy.FIRST, firstFooter);

Once I generate my docx file I could see my default header/footer on every page including first one. But if I select to use different header/footer for the first page – my first header and footer apperes correctly. How could I make this happens automaticaly via code? And is there any appropriate documentation with examples about POI?

Answer

If you want to set a first page header in a section, you must enter a title page tag in section properties tag (w:sectPr). The title page tag can be empty, but it is necessary. In your case, you can add only 2 code lines:

CTSectPr sect = document.getDocument().getBody().getSectPr();
sect.addNewTitlePg();

`Best regards!

We are here to answer your question about POI enable different header/footer for the first page in word docx file - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji