在 Microsoft Word 中,我们可以将段落缩进设置为左缩进、右缩进、首行缩进或悬挂缩进。本文,我们将演示如何使用 Spire.Doc for Java 实现此功能。
安装 Spire.Doc for Java
首先,您需要在 Java 程序中添加 Spire.Doc.jar 文件作为依赖项。您可以从这个链接下载 JAR 文件;如果您使用 Maven,则可以通过在 pom.xml 文件中添加以下代码导入 JAR 文件。
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>13.3.0</version>
</dependency>
</dependencies>
设置段落缩进
Spire.Doc for Java 提供了 ParagraphFormat 类用于处理段落格式。您可以使用 Paragraph.getFormat() 方法获取 ParagraphFormat 类的对象,然后使用下面的方法设置对应的段落缩进:
缩进方式 | 方法 | 方法解释 |
左缩进 | ParagraphFormat.setLeftIndent(float value) | 根据设置的缩进量使段落从左边缩进 |
右缩进 | ParagraphFormat.setRightIndent(float value) | 根据设置的缩进量使段落从右边缩进 |
首行缩进 | ParagraphFormat.setFirstLineIndent(float value) | 将段落的第一行缩进 |
悬挂缩进 | ParagraphFormat.setFirstLineIndent(float negativeValue) | 将段落的第一行置于页边空白处,然后缩进该段后面的每一行 |
下面实现段落缩进的方法步骤:
- 创建 Document 类的实例。
- 使用 Document.loadFromFile() 方法加载 Word 文档。
- 使用 Document.getSections.get() 方法通过索引获取所需的section。
- 使用 Section.getParagraphs.get() 方法通过索引获取所需的段落。
- 使用 Paragraph.getFormat() 方法获取 ParagraphFormat 对象。
- 调用上表中列出的方法来设置对象的段落缩进。
- 使用 Document.saveToFile() 方法保存结果文档。
- Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.formatting.ParagraphFormat;
public class IndentParagraph {
public static void main(String[] args) {
//创建Document类的实例
Document document= new Document();
//加载Word文档
document.loadFromFile("Input.docx");
//获取第一节
Section section = document.getSections().get(0);
//获取第二段,设置左缩进
Paragraph para = section.getParagraphs().get(1);
ParagraphFormat format = para.getFormat();
format.setLeftIndent(30);
//获取第三段,设置右缩进
para = section.getParagraphs().get(2);
format = para.getFormat();
format.setRightIndent(30);
//获取第四段,设置首行缩进
para = section.getParagraphs().get(3);
format = para.getFormat();
format.setFirstLineIndent(30);
//获取第五段,设置悬挂缩进
para = section.getParagraphs().get(4);
format = para.getFormat();
format.setFirstLineIndent(-30);
//保存结果文档
document.saveToFile("SetParagraphIndents.docx", FileFormat.Docx_2013);
}
}
设置段落缩进后的效果图:
申请临时License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请 该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。 获取有效期30天的临时许可证。