跳到主要内容

【已解决】docx4j 插入分页符

使用的版本是:

<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>6.1.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
</dependency>

代码

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.*;

private static void addPageBreak(WordprocessingMLPackage wordMLPackage) {
// 创建分页符元素
Br pageBreak = new Br();
pageBreak.setType(STBrType.PAGE);

// 创建段落和运行元素,并将分页符添加到运行元素
P paragraph = new P();
R run = new R();
run.getContent().add(pageBreak);

// 将运行元素添加到段落
paragraph.getContent().add(run);

// 将段落添加到文档末尾
wordMLPackage.getMainDocumentPart().getContent().add(paragraph);
}