页眉可编辑颜色与字体选择
页脚显示当前页码与页码的总数
页眉插入的方法:
XWPFDocument document = new XWPFDocument();
CT_Ftr footer = new CT_Ftr();
XWPFParagraph paragraph = new XWPFParagraph(footer.AddNewP(), document);
paragraph.Alignment = ParagraphAlignment.CENTER;
//paragraph.SetFontFamily(fontFamily, FontCharRange.None);
// 添加字段表示当前页数
XWPFRun runCurrentPage = paragraph.CreateRun();
runCurrentPage.SetFontFamily("宋体", FontCharRange.None);
runCurrentPage.SetColor("000000");
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.begin;
runCurrentPage.GetCTR().AddNewInstrText().Value = "PAGE";
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.separate;
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.end;
页码的插入方法:
XWPFDocument document = new XWPFDocument();
CT_Ftr footer = new CT_Ftr();
XWPFParagraph paragraph = new XWPFParagraph(footer.AddNewP(), document);
paragraph.Alignment = ParagraphAlignment.CENTER;
//paragraph.SetFontFamily(fontFamily, FontCharRange.None);
// 添加字段表示当前页数
XWPFRun runCurrentPage = paragraph.CreateRun();
runCurrentPage.SetFontFamily("宋体", FontCharRange.None);
runCurrentPage.SetColor("000000");
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.begin;
runCurrentPage.GetCTR().AddNewInstrText().Value = "PAGE";
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.separate;
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.end;
// 添加分隔符 "/"
XWPFRun runSeparator = paragraph.CreateRun();
runSeparator.SetText(" / ");
// 添加字段表示总页数
XWPFRun runTotalPages = paragraph.CreateRun();
runTotalPages.SetFontFamily("宋体", FontCharRange.None);
runTotalPages.SetColor("000000");
runTotalPages.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.begin;
runTotalPages.GetCTR().AddNewInstrText().Value = "NUMPAGES";
runTotalPages.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.separate;
runTotalPages.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.end;
// 创建页脚关系
XWPFRelation relation = XWPFRelation.FOOTER;
XWPFFooter myFooter = (XWPFFooter)document.CreateRelationship(relation, XWPFFactory.GetInstance(), document.FooterList.Count + 1);
myFooter.SetHeaderFooter(footer);
在节属性中添加页脚引用
CT_SectPr sectPr = document.Document.body.sectPr;
CT_HdrFtrRef footerRef = sectPr.AddNewFooterReference();
footerRef.type = ST_HdrFtr.@default;
footerRef.id = myFooter.GetPackageRelationship().Id;