在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—