Set Alignment for Paragraphs in Word in Java

Setting alignment for paragraphs is one of the most simple but necessary steps to make a well formatted Word document. This article will show you how to set left, centered, right and justified alignment for paragraphs in a Word document by using Free Spire.Doc for Java.

Installation

Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

Method 2: You can also 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>3.9.0</version>
</dependency>
</dependencies>

Code Snippet

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class ParagraphAlighment {
public static void main(String[] args){
//Instantiate a Document object
Document document = new Document();

//Add a section
Section section = document.addSection();

//Add a paragraph and make it left aligned
Paragraph paragraph = section.addParagraph();
paragraph.appendText("This paragraph is left-aligned");
paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);

//Add a paragraph and make it centered
paragraph = section.addParagraph();
paragraph.appendText("This paragraph is centered");
paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

//Add a paragraph and make it right alighed
paragraph = section.addParagraph();
paragraph.appendText("This paragraph is right-aligned");
paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

//Add a paragraph and make it justified
paragraph = section.addParagraph();
paragraph.appendText("This paragraph is justified");
paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);

//Save the resultant document
document.saveToFile("ParagraphAlignment.docx", FileFormat.Docx_2013);
}
}

Output

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store