This is the code that I change header of a certain section. however, it could also changed some header of sections that i don’t want to. seems like it remove the original one and continue
private void generateHeader(Section section, String text)
throws Exception {
Document document = (Document) section.getDocument();
HeaderFooter headerFirst = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_FIRST);
if (headerFirst == null) {
headerFirst = new HeaderFooter(document, HeaderFooterType.HEADER_FIRST);
section.getHeadersFooters().add(headerFirst);
} else {
// todo 把header删除
headerFirst.getChildNodes(NodeType.PARAGRAPH, true).clear();
}
Paragraph headerParagraph = new Paragraph(document);
if (text != null) {
Run runFirst = new Run(document, text);
headerParagraph.appendChild(runFirst);
}
FieldStyleRef fieldStyleRefFirst = (FieldStyleRef) headerParagraph.appendField(FieldType.FIELD_STYLE_REF, false);
fieldStyleRefFirst.setStyleName("customHeading_1");
// 将段落添加到第一页的页眉
headerFirst.appendChild(headerParagraph);
// 处理其他页的主要页眉
HeaderFooter headerPrimary = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);
if (headerPrimary == null) {
headerPrimary = new HeaderFooter(document, HeaderFooterType.HEADER_PRIMARY);
section.getHeadersFooters().add(headerPrimary);
} else {
headerPrimary.getChildNodes(NodeType.PARAGRAPH, true).clear();
}
// 创建新的段落和 StyleRef 字段
Paragraph paraPrimary = new Paragraph(document);
// 插入指定的文字,例如 "第一章"
if (text != null) {
Run runPrimary = new Run(document, text);
paraPrimary.appendChild(runPrimary);
}
// 创建 StyleRef 字段并插入到段落中
FieldStyleRef fieldStyleRefPrimary = (FieldStyleRef) paraPrimary.appendField(FieldType.FIELD_STYLE_REF, false);
fieldStyleRefPrimary.setStyleName("customHeading_1");
// 将段落添加到主要页眉
headerPrimary.appendChild(paraPrimary);
ParagraphUtils.setHeaderParaFormat(headerParagraph);
ParagraphUtils.setHeaderParaFormat(paraPrimary);
}
like this
original:
changed one :
the ‘符号和缩略语说明’ is the header of the last section.
how can i fix it ?