Line spacing is the white space between each line in a paragraph, while paragraph spacing is the white space between each paragraph. You can increase the spacing between the lines or paragraphs in your document to improve readability, or you can also reduce the spacing to fit more text on the page. This article will share how to set spacing between paragraphs and how to set line spacing within a paragraph programmatically using a free Java library.
Introduction of the free library:
https://www.e-iceblue.com/Introduce/free-doc-for-java.html
Installation
Method 1: Download the free API and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Set Paragraph Spacing
Free Spire.Doc for Java offers the Paragraph.getFormat().setAfterSpacing() and Paragraph.getFormat().setBeforeSpacing() methods for you to set the spacing before and after paragraphs.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
public class SetParagraphSpacing {
public static void main(String[] args) {
//Create a Document instance
Document doc = new Document();
//Load a sample document
doc.loadFromFile("Herman.docx");
//Get the first section
Section section = doc.getSections().get(0);
//Get a specified paragraph
Paragraph para = section.getParagraphs().get(0);
//Set paragraph after spacing
para.getFormat().setAfterSpacing(50f);
//Save the document
doc.saveToFile("out/SetParagraphSpacing.docx", FileFormat.Docx_2013);
}
}
Set Line Spacing
To set the line spacing within a paragraph, you can use the Paragraph.getFormat().setLineSpacing() method.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
public class SetLineSpacing {
public static void main(String[] args) {
//Create a Document instance
Document doc = new Document();
//Load a sample document
doc.loadFromFile("Herman.docx");
//Get the first section
Section section = doc.getSections().get(0);
//Get a specified paragraph
Paragraph para = section.getParagraphs().get(0);
//Set line spacing
para.getFormat().setLineSpacing(30f);
//Save the document
doc.saveToFile("out/SetLineSpacing.docx", FileFormat.Docx_2013);
}
}