Java如何在Word中插入分页符?
作者:SunnyJourney
时间:2023-04-26
来源:互联网
浏览:0
程序环境在程序中导入jar,如下两种方法:方法1:手动引入。将FreeSpire.DocforJava下载到本地,解压,找到lib文件夹下的Spire.Doc.jar文件。在IDEA中打开如下界面,将本地路径中的jar文件引入Java程序:方法2(推荐使用):通过Maven仓库下载。如下配置pom.xml:com.e-icebluehttps://repo.e-iceblue.cn/repository/maven-public/e-icebluespire.doc.free5.2.0插入分页符1.在指定
程序环境
在程序中导入jar,如下两种方法:
方法1:手动引入。将 Free Spire.Doc for Java 下载到本地,解压,找到lib文件夹下的Spire.Doc.jar文件。在IDEA中打开如下界面,将本地路径中的jar文件引入Java程序:

方法2(推荐使用):通过 Maven 仓库下载。如下配置pom.xml:
com.e-iceblue https://repo.e-iceblue.cn/repository/maven-public/ e-iceblue spire.doc.free 5.2.0
插入分页符
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);
}
}效果图

作者最新文章
图几
2026-09-16 17:43
SQL中ROUND函数对0.5的处理机制及强制四舍五入方法
2026-09-15 14:19
JS金额计算怎么避免四舍五入误差
2026-09-14 17:32
韩国8月携号转网数据:Galaxy Z8系列iPhone用户转化率约为Z7系列2倍
2026-09-08 17:02
AE基础教程:如何创建合成并制作关键帧动画
2026-09-04 09:27
上一篇:
Java如何利用泛型实现数组排序
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















