【参考】https://www.cnblogs.com/Yesi/p/11010805.html
本篇文章将介绍通过java程序来添加Word页眉页脚的方法。鉴于在不同文档中,对页眉页脚的操作要求不同,文章将分别从以下几种情况来阐述:
1.添加页眉页脚
- 添加图片到页眉
- 添加文本到页眉
- 添加页码
2.设置奇偶页不同的页眉页脚
3.设置首页页眉页脚不同
4.不连续设置页码(即对不同章节的内容设置不同页码)
5.锁定页眉页脚(不可编辑页眉页脚)
6.删除页眉页脚
- 删除全部页眉页脚
- 删除首页页眉页脚
使用工具:Free Spire.Doc for Java
方法一:直接获取文件包里的jar文件,导入到程序(需要先下载文件包)。
方法二:通过Maven导入到程序。
【示例1】添加页眉页脚(文本、图片、页码)
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.DocPicture; import com.spire.doc.fields.TextRange; import java.awt.*; public class AddHeaderFooter { public static void main(String[]args){ //加载需要添加页眉页脚的文档 Document doc= new Document("test.docx"); Section sec = doc.getSections().get(0); //调用方法添加页眉页脚 AddHeaderFooter(sec); //保存文档 doc.saveToFile("AddHeaderFooter.docx"); } //自定义方法来添加图片、文字页眉及页码 private static void AddHeaderFooter(Section sec){ //加载图片添加到页眉,并设置图片在段落中的对齐方式 HeaderFooter header = sec.getHeadersFooters().getHeader(); Paragraph hpara= header.addParagraph(); DocPicture pic =hpara.appendPicture("1.png"); pic.setHorizontalAlignment(ShapeHorizontalAlignment.Left); pic.setVerticalOrigin(VerticalOrigin.Top_Margin_Area); pic.setVerticalAlignment(ShapeVerticalAlignment.Center); //添加文字到页眉,并设置字体、字号、字体加粗、对齐方式 TextRange txt = hpara.appendText("青年时报"); txt.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None); txt.getCharacterFormat().setTextColor(Color.GRAY); txt.getCharacterFormat().setFontName("仿宋"); txt.getCharacterFormat().setFontSize(12f); txt.getCharacterFormat().setBold(true); hpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); //设置图片的文本环绕方式、页眉底部边线(粗细、间距) pic.setTextWrappingStyle(TextWrappingStyle.Behind); hpara.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single); hpara.getFormat().getBorders