I want to generate different headers in first page and other pages in poi word, So I used XWPFHeaderFooterPolicy.FIRST and XWPFHeaderFooterPolicy.DEFAULT. when I using XWPFHeaderFooterPolicy.DEFAULT I can insert my header successfully, but when I change to XWPFHeaderFooterPolicy.FIRST, I cannot see there is a header in my first page, this is my code in below, what's wrong with it? thanks!
XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.FIRST);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("header");
There is nothing in that class to tell Word to display different first page headers. You will need the most recent version of POI, and then create the header from XWPFDocument using:
Otherwise you need to break into the CT classes and in the section properties set the
titlePg
property. I don't recommend this approach though as it is likely to change.That there is a different header set for first page only, means not that this header will also be shown. In
Word
GUI there is a checkbox[x] Different First Page
inHeader & Footer Tools
to achieve that.And according Office Open XML Part 4 - Markup Language Reference there must a boolean XML element
titlePg
be set to determine that there is a title page present.In actual final
apache poi
version 3.15 this XML elementtitlePg
can only be set using underlying low level objects usingdoc.getDocument().getBody().getSectPr().addNewTitlePg();
.But
apache poi
version 3.16 Beta 2 hasdoc.createHeader(HeaderFooterType.FIRST);
which setstitlePg
flag in XML.Complete example:
But in my opinion the setting
titlePg
flag in XML automatically whileHeaderFooterType.FIRST
is created is not correct. SinceWord
can toggle between[x] Different First Page
and[] Different First Page
,apache poi
should also be able to do so. So the setting thetitlePg
flag should be a method inXWPFDocument
.