Java 添加Word页眉、页脚

本篇文章将介绍通过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().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】设置奇偶页页眉页脚不同

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class HeaderFooterForOddAndEvenPages {
    public static void main(String[] args){
        //加载测试文档
        Document doc = new Document("test.docx");
        Section sec = doc.getSections().get(0);

        //设置奇偶页页眉页脚不同
        sec.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter(true);

        //设置奇数页页眉页脚
        HeaderFooter oddheader = sec.getHeadersFooters().getOddHeader();
        Paragraph para1 = oddheader.addParagraph();
        TextRange textRange1 = para1.appendText("奇数页页眉");
        para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
        textRange1.getCharacterFormat().setTextColor(Color.ORANGE);
        textRange1.getCharacterFormat().setBold(true);
        HeaderFooter oddfooter = sec.getHeadersFooters().getFooter();
        Paragraph para2 = oddfooter.addParagraph();
        TextRange textRange2 = para2.appendText("奇数页页脚");
        para2.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
        textRange2.getCharacterFormat().setTextColor(Color.ORANGE);
        textRange2.getCharacterFormat().setBold(true);

        //设置偶数页页眉页脚
        HeaderFooter evenheader = sec.getHeadersFooters().getEvenHeader();
        Paragraph para3 = evenheader.addParagraph();
        TextRange textRange3 = para3.appendText("偶数页页眉");
        para3.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
        textRange3.getCharacterFormat().setTextColor(Color.BLUE);
        textRange3.getCharacterFormat().setBold(true);
        HeaderFooter evenfooter = sec.getHeadersFooters().getEvenFooter();
        Paragraph para4 = evenfooter.addParagraph();
        TextRange textRange4 = para4.appendText("偶数页页脚");
        para4.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
        textRange4.getCharacterFormat().setTextColor(Color.BLUE);
        textRange4.getCharacterFormat().setBold(true);

        //保存文档
        doc.saveToFile("result.docx",FileFormat.Docx_2010);
    }

}
奇偶数页眉页脚设置效果:

 

【示例3】设置首页页眉页脚不同

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class HeaderFooterDifferentFromFirstPage {
    public static void main(String[] args){
        //加载测试文的
        Document doc = new Document("test.docx");
        Section sec = doc.getSections().get(0);

        //设置首页页眉页脚不同
        sec.getPageSetup().setDifferentFirstPageHeaderFooter(true);

        //添加首页页眉页脚
        HeaderFooter firstpageheader = sec.getHeadersFooters().getFirstPageHeader();
        Paragraph para1 = firstpageheader.addParagraph();
        TextRange textRange1 = para1.appendText("首页页眉");
        para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        textRange1.getCharacterFormat().setBold(true);
        textRange1.getCharacterFormat().setTextColor(Color.GREEN);
        HeaderFooter firstpagefooter = sec.getHeadersFooters().getFirstPageFooter();
        Paragraph para2 = firstpagefooter.addParagraph();
        TextRange textRange2 = para2.appendText("首页页脚");
        para2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        textRange2.getCharacterFormat().setBold(true);
        textRange2.getCharacterFormat().setTextColor(Color.GREEN);


        //添加页眉页脚到其他页面
        Paragraph para3 = sec.getHeadersFooters().getHeader().addParagraph();
        para3.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        TextRange textRange3 = para3.appendText("非首页页眉");
        textRange3.getCharacterFormat().setBold(true);
        Paragraph para4 = sec.getHeadersFooters().getFooter().addParagraph();
        para4.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        TextRange textRange4 = para4.appendText("非首页页脚");
        textRange4.getCharacterFormat().setBold(true);

        //保存文档
        doc.saveToFile("result2.docx",FileFormat.Docx_2010);
    }
}

页眉页脚设置效果:

 

【示例4】不连续设置页码

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.PageNumberStyle;
import com.spire.doc.documents.Paragraph;

public class DifferentPageNumber {
    public static void main(String[]args){
        //加载测试文档
        Document doc = new  Document("test.docx");

        //添加页码到第一节
        HeaderFooter footer= doc.getSections().get(0).getHeadersFooters().getFooter();
        Paragraph footerpara = footer.addParagraph();
        footerpara.appendField("Page Number",FieldType.Field_Page);
        footerpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
        //设置第一节页码数字格式为罗马数字
        doc.getSections().get(0).getPageSetup().setPageNumberStyle(PageNumberStyle.Roman_Lower);

        //设置第二节页码数字格式为阿拉伯数字
        doc.getSections().get(1).getPageSetup().setPageNumberStyle(PageNumberStyle.Arabic);
        //设置第二节页码从新开始编码,并设置起始页码数字
        doc.getSections().get(1).getPageSetup().setRestartPageNumbering(true);
        doc.getSections().get(1).getPageSetup().setPageStartingNumber(1);

        //保存文档
        doc.saveToFile("restartnumbering.docx",FileFormat.Docx_2010);
    }
}

页码设置效果:

 

【示例5】锁定页眉页脚

import com.spire.doc.*;

public class LockHeaderFooter {
    public static void main(String[]args){
       //加载测试文档
        Document doc = new Document("sample.docx");

        //获取第一节
        Section sec = doc.getSections().get(0);

        //设置保护类型及密码
        doc.protect(ProtectionType.Allow_Only_Form_Fields,"123");
        sec.setProtectForm(false);

        //保存文档
        doc.saveToFile("LockHeaderFooter.docx",FileFormat.Docx_2010);
    }
}

锁定页眉页脚后,文档中除页眉页脚外其他内容可正常编辑。

 

【示例6】删除页眉页脚

  1. 删除所有页眉页脚
import com.spire.doc.*;

public class DeleteAllHeaderFooter {
    public static void main(String[]args){
        //加载测试文档
        Document doc = new Document("sample.docx");
        //获取第一节
        Section sec = doc.getSections().get(0);

        //删除页眉
        sec.getHeadersFooters().getHeader().getChildObjects().clear();

        //删除页脚
        sec.getHeadersFooters().getFooter().getChildObjects().clear();

        //保存文档
        doc.saveToFile("DeleteAllHeaderFooter.docx");
    }
}

删除效果前后对比:

 

2. 删除首页页眉页脚

import com.spire.doc.*;

public class DeleteHeaderFooterOfFirstPage {
    public static void main(String[]args){
        //加载测试文档
        Document doc = new Document("sample.docx");
        //获取第一节
        Section sec = doc.getSections().get(0);

        //设置首页页眉页脚不同
        sec.getPageSetup().setDifferentFirstPageHeaderFooter(true);

        //删除首页页眉页脚
        sec.getHeadersFooters().getFirstPageHeader().getChildObjects().clear();
        sec.getHeadersFooters().getFirstPageFooter().getChildObjects().clear();

        //保存文档
        doc.saveToFile("DeleteHeaderFooterOfFirstPage.docx",FileFormat.Docx_2010);
    }
}

首页页眉页脚删除效果:

(本文完)

转载请注明出处!!

 

要在 Word 文档中添加页眉页脚,可以使用 Apache POI 的 XWPF API。下面是一个简单的示例代码,说明如何使用 XWPF API 在 Word 文档中添加页眉页脚: ```java import org.apache.poi.xwpf.usermodel.*; import java.io.*; public class WordDocument { public static void main(String[] args) throws Exception { // 创建一个新的 Word 文档 XWPFDocument document = new XWPFDocument(); // 添加一个新的页面 XWPFParagraph para = document.createParagraph(); XWPFRun run = para.createRun(); run.setText("This is a new page."); // 添加页眉 CTP ctP = CTP.Factory.newInstance(); XWPFParagraph headerParagraph = new XWPFParagraph(ctP, document); XWPFHeader header = document.createHeader(XWPFHeaderFooterPolicy.DEFAULT); header.getParagraphArray(0).setBorderBottom(Borders.SINGLE); // 设置页眉的边框 header.getParagraphArray(0).setAlignment(ParagraphAlignment.CENTER); // 设置页眉的对齐方式 CTText ctText = CTText.Factory.newInstance(); ctText.setStringValue("This is the header text."); headerParagraph.getCTP().setPPr(header.getParagraphArray(0).getCTP().getPPr()); ctP.setRArray(0, headerParagraph.createRun().getCTR()); // 添加页脚 CTP ctP2 = CTP.Factory.newInstance(); XWPFParagraph footerParagraph = new XWPFParagraph(ctP2, document); XWPFFooter footer = document.createFooter(XWPFHeaderFooterPolicy.DEFAULT); footer.getParagraphArray(0).setBorderTop(Borders.SINGLE); // 设置页脚的边框 footer.getParagraphArray(0).setAlignment(ParagraphAlignment.CENTER); // 设置页脚的对齐方式 CTText ctText2 = CTText.Factory.newInstance(); ctText2.setStringValue("This is the footer text."); footerParagraph.getCTP().setPPr(footer.getParagraphArray(0).getCTP().getPPr()); ctP2.setRArray(0, footerParagraph.createRun().getCTR()); // 保存 Word 文档 FileOutputStream out = new FileOutputStream("example.docx"); document.write(out); out.close(); } } ``` 在上面的示例代码中,我们创建了一个新的 Word 文档,并添加了一个新的页面。然后,我们通过 XWPF API 添加页眉页脚。最后,我们将 Word 文档保存到本地文件系统中。 需要注意的是,上面的示例代码中,我们使用了 XWPFHeaderFooterPolicy.DEFAULT,这表示我们在默认的页眉页脚位置添加了新的页眉页脚。如果你想要在不同的位置添加页眉页脚,可以使用不同的 XWPFHeaderFooterPolicy。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值