我正在尝试创建一个word文档,其中我将仅在第一页中没有页脚,其余页面有页脚。我编写了以下代码(我还尝试更改-back-footer
和footerFirst
对象的创建顺序),但这没有帮助。我仍然在所有页面上使用默认页脚。
我应该如何禁用第一页的页脚?提前感谢。
private XWPFDocument initDocument(String FILE) throws Exception{
XWPFDocument document = new XWPFDocument();
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) headerFooterPolicy = document.createHeaderFooterPolicy();
// create header start
XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
//XWPFParagraph paragraph = footer.createParagraph();
XWPFParagraph paragraph = footer.getParagraphArray(0);
if (paragraph == null)
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph.createRun();
run.setFontSize(11);
run.setFontFamily("Times New Roman");
run.setText("Some company info in the footer");
XWPFFooter footerFirst = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.FIRST);
paragraph = footerFirst.getParagraphArray(0);
if (paragraph == null)
paragraph = footerFirst.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText(" ");
return document;
}
仅为第一页设置了不同的标题,这意味着不会显示此标题。在WordGUI
中,Header中有一个复选框[x]不同的首页
根据Office OpenXML第4部分-标记语言参考,必须设置一个布尔XML
元素titlePg
来确定存在标题页。
在旧的apache poi版本中,使用XWPFHeaderFoterPolicy这个XML
元素titlePg只能使用文档. getDocument().getBody().getSectPr().addNewTitlePg();的底层对象来设置。
但是使用当前的apache poi
版本(从3.16
开始),不需要直接使用XWPFHeaderFoterPolicy
。现在有XWPFDocument. createHeader
和XWPFDocument.createFoter
使用HeaderFoterType
。当使用HeaderFoterType.FIRST
时,这会在XML
中设置titlePg
标志。
设置和使用HeaderFoterType. FIRST
和HeaderFoterType.DEFAULT
的完整示例:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
public class CreateWordFooters {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
// the body content
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The Body... first page");
paragraph = document.createParagraph();
run=paragraph.createRun();
run.addBreak(BreakType.PAGE);
run.setText("The Body... second page");
// create first page footer
XWPFFooter footer = document.createFooter(HeaderFooterType.FIRST);
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText("First page footer...");
// create default footer
footer = document.createFooter(HeaderFooterType.DEFAULT);
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("Default footer...");
FileOutputStream out = new FileOutputStream("CreateWordFooters.docx");
document.write(out);
out.close();
document.close();
}
}