顾名思义,字间距指的是行内文字之间的距离,而行间距的意思则是段落中各行文字之间的垂直距离。我们可以通过调整字间距和行间距的方式来改变文档的页面结构,从而达到凸显某些文本或缩进字符距离,节省空间的效果。本文将演示如何使用Free Spire.Doc for Java控件在Java程序中设置Word文档的字间距和行间距。

创建开发环境

首先,我们需要安装和配置JDK和Intellij IDEA来创建代码的运行环境,接着在E-iceblue中文网站上获取Free Spire.Doc for Java控件,解压后在lib文件夹找到Spire.Doc.jar,最后手动将Jar包导入IDEA。除此之外,也可以直接在IDEA中创建Maven仓库,然后在pom.xml中键入以下代码,以此来导入相应Jar包。

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

代码示例

import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.fields.TextRange; import java.awt.*; public class SetSpacing { public static void main(String[] args) { //加载示例文档 Document document= new Document("C:\\Users\\Test1\\Desktop\\Sample.docx"); //添加新段落并设置段落文本和字体样式 Paragraph para = new Paragraph(document); TextRange textRange1 = para.appendText("新加段落,设置行间距和字间距"); textRange1.getCharacterFormat().setTextColor(Color.BLUE); textRange1.getCharacterFormat().setFontSize(15); //设置段前段后间距 para.getFormat().setBeforeAutoSpacing(false); para.getFormat().setBeforeSpacing(10); para.getFormat().setAfterAutoSpacing(false); para.getFormat().setAfterSpacing(10); //设置字间距 for (DocumentObject object :(Iterable<DocumentObject>)para.getChildObjects()) { TextRange textRange= (TextRange) object; textRange.getCharacterFormat().setCharacterSpacing(3f); } //插入新加段落 document.getSections().get(0).getParagraphs().insert(2, para); //保存文档 document.saveToFile("output/SetSpacing.docx", FileFormat.Docx); } }

设置效果

如何设置java的字体大小(设置Word文档的字间距和行间距)(1)

,