本文介绍如何使用spire.doc for java添加文字、图片、横线和页码到word文档中的页眉或页脚。
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.docpicture;
import com.spire.doc.fields.textrange;
public class insertheaderandfooter {
public static void main(string[] args) {
//加载word文档
document document = new document();
document.loadfromfile("c:\\users\\administrator\\desktop\\sample.docx");
//获取第一个section
section section = document.getsections().get(0);
//调用insertheaderandfooter方法插入页眉页脚到第一个section
insertheaderandfooter(section);
//保存文档
document.savetofile("output/headerandfooter.docx", fileformat.docx);
}
private static void insertheaderandfooter(section section) {
//分别获取section的页眉页脚
headerfooter header = section.getheadersfooters().getheader();
headerfooter footer = section.getheadersfooters().getfooter();
//添加段落到页眉
paragraph headerparagraph = header.addparagraph();
//插入图片到页眉的段落
docpicture headerpicture = headerparagraph.appendpicture("c:\\users\\administrator\\desktop\\logo.png");
headerpicture.sethorizontalalignment(shapehorizontalalignment.left);
headerpicture.setverticalorigin(verticalorigin.top_margin_area);
headerpicture.setverticalalignment(shapeverticalalignment.bottom);
//添加文字到页眉的段落
textrange text = headerparagraph.appendtext("demo of spire.doc");
text.getcharacterformat().setfontname("arial");
text.getcharacterformat().setfontsize(10);
text.getcharacterformat().setitalic(true);
headerparagraph.getformat().sethorizontalalignment(horizontalalignment.right);
//设置文字环绕方式
headerpicture.settextwrappingstyle(textwrappingstyle.behind);
//设置页眉段落的底部边线样式
headerparagraph.getformat().getborders().getbottom().setbordertype(borderstyle.single);
headerparagraph.getformat().getborders().getbottom().setlinewidth(1f);
//添加段落到页脚
paragraph footerparagraph = footer.addparagraph();
//添加field_page和field_num_pages域到页脚段落,用于显示当前页码和总页数
footerparagraph.appendfield("page number", fieldtype.field_page);
footerparagraph.appendtext(" of ");
footerparagraph.appendfield("number of pages", fieldtype.field_num_pages);
footerparagraph.getformat().sethorizontalalignment(horizontalalignment.right);
//设置页脚段落的顶部边线样式
footerparagraph.getformat().getborders().gettop().setbordertype(borderstyle.single);
footerparagraph.getformat().getborders().gettop().setlinewidth(1f);
}
}