Java 在Word指定段落/文本位置插入分页符

在Word插入分页符可以在指定段落后插入,也可以在特定文本位置处插入。本文,将以Java代码来操作以上两种文档分页需求。下面是详细方法及步骤。

【程序环境】

在程序中导入jar,如下两种方法:

方法1手动引入。将 Free Spire.Doc for Java 下载到本地,解压,找到lib文件夹下的Spire.Doc.jar文件。在IDEA中打开如下界面,将本地路径中的jar文件引入Java程序:

方法2(推荐使用):通过 Maven 仓库下载。如下配置pom.xml:

<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>

【插入分页符】

1.在指定段落后插入分页符

Java

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph; public class PageBreak1 {
public static void main(String[] args) {
//创建Document类的对象
Document document = new Document();
//加载Word文档
document.loadFromFile("test.docx"); //获取第一节
Section section = document.getSections().get(0);
//获取第一节中的第3个段落
Paragraph paragraph = section.getParagraphs().get(2); //添加分页符
paragraph.appendBreak(BreakType.Page_Break); //保存文档
document.saveToFile("output.docx", FileFormat.Docx_2013);
}
}

2.在指定文本位置后插入分页符

Java

import com.spire.doc.Break;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange; public class PageBreak2 {
public static void main(String[] args) {
//创建Document类的实例
Document document = new Document(); //加载Word文档
document.loadFromFile("test.docx"); //查找指定文本
TextSelection selection = document.findString("“东盟共同体”宣告成立。", true, true);
//获取查找的文本范围
TextRange range = selection.getAsOneRange();
//获取文本范围所在的段落
Paragraph paragraph = range.getOwnerParagraph(); //获取文本范围在段落中的位置索引
int index = paragraph.getChildObjects().indexOf(range); //创建分页
Break pageBreak = new Break(document, BreakType.Page_Break); //在查找的文本位置后面插入分页符
paragraph.getChildObjects().insert(index + 1, pageBreak); //保存文档
document.saveToFile("InsertPageBreakAfterText.docx", FileFormat.Docx_2013);
}
}

—END—

Java 在Word指定段落/文本位置插入分页符的相关教程结束。

相关推荐:

如何根据前一个连续段落的值修改当前数字序列

本文介绍如何在Pandas中识别数值的连续段(streak),并基于前一段的值批量修改当前段——例如,将紧跟在1段之后的所有2段统一替换为1,同时保持其他值(如-1)不变。 本文介绍如何在pandas中识别数值的连续段(streak),并基于前一段的值批量修改当前段——例如,将紧跟在`1`段之后的所...

如何正确删除 XML 文件中的指定元素节点

使用Python的xml.etree.ElementTree删除XML元素时,直接通过索引delroot[i][j]无法可靠移除节点,因其不触发父节点的结构更新;应改用find()定位目标元素后调用parent.remove(child)方法。 使用python的`xml.etree.element...

Python中如何填充DataFrame中的空值_通过fillna函数指定填充策略

fillna默认不填充,必须显式传入value;支持字典分列填充、ffill/bfill前后向填充、interpolate数值插值,但需据空值语义谨慎选择策略。 fillna函数的基本用法和默认行为 fillna是pandas中最直接的空值填充方法,但它不是“智能补全”,而是按你指定的值或策略做静态...

如何优化Python Django中的Large Page分页性能_使用键值分页替代offset

Seek分页是解决大页码性能崩坏最有效的手段,尤其当页码超过500或OFFSET>10000时,可将查询从秒级降至毫秒级;其核心是用上一页最后记录的排序字段值作游标,避免OFFSET扫描丢弃大量数据,需配合复合索引及非空约束,并舍弃页码跳转、总页数等需求。 直接结论:用Seek分页(键值分页)...