Java 添加Word页眉页脚
1、导入方法1:通过E-iceblue官网下载Free Spire.Doc for Java 的文件包并解压,在IDEA程序中导入Spire.Doc.jar文件(jar文件在文件夹lib下获取)
2、导入方法2:通过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().getBottom().setLineWidth(0.5f);
hpara.getFormat().getBorders().setSpace(2f);
//添加页码到页脚,并设置页脚对齐方式,顶部边线粗细、间距
HeaderFooter footer = sec.getHeadersFooters().getFooter();
Paragraph fpara= footer.addParagraph();
fpara.appendField("页码",FieldType.Field_Page);
fpara.appendText("/");
fpara.appendField("总页数",FieldType.Field_Num_Pages);
fpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
fpara.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
fpara.getFormat().getBorders().getTop().setLineWidth(1f);
fpara.getFormat().getBorders().getTop().setSpace(2f);
}
}
2、页眉页脚添加效果:

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:96
阅读量:112
阅读量:178
阅读量:37
阅读量:108