DEV Community 👩‍💻👨‍💻

E-iceblue Product Family
E-iceblue Product Family

Posted on

How to Indent a Paragraph in Word in Java

In this article, we will demonstrate how to indent paragraphs in Word in Java applications using Spire.Doc for Java. Spire.Doc for Java offers ParagraphFormat.setLeftIndent(float value) method to set the paragraph left indents and ParagraphFormat.setRightIndent(float value) for right indents. The ParagraphFormat.setFirstLineIndent(float value) method can be used to set both hanging and first line indents. Negative value for this property is for the hanging indent and positive value for the first line indent of the paragraph.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

Enter fullscreen mode Exit fullscreen mode

Using the code

The following are the steps to set paragraph indents in Word:

  • Create a Document instance.
  • Load a Word document using Document.loadFromFile() method.
  • Get the desired section by its index using Document.getSections.get() method.
  • Get the desired paragraph by index using Section.getParagraphs.get() method.
  • Get the ParagraphFormat object using Paragraph.getFormat() method.
  • Call the methods to set paragraph indents with the object.
  • Save the result document using Document.saveToFile() method.

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 Test {
    public static void main(String[] args) throws Exception {
        //Create a Document instance
        Document document= new Document();
        //Load a Word document

        //Get the first section
        Section section = document.getSections().get(0);

        //Get the first paragraph and set left indent, right indent
        Paragraph para = section.getParagraphs().get(0);
        ParagraphFormat format = para.getFormat();

        //Get the second paragraph and set first line indent
        para = section.getParagraphs().get(1);
        format = para.getFormat();

        //Get the third paragraph and set hanging indent
        para = section.getParagraphs().get(2);
        format = para.getFormat();

        //Save the result document
        document.saveToFile("SetParagraphIndents.docx", FileFormat.Docx_2013);
Enter fullscreen mode Exit fullscreen mode

Image description

Latest comments (0)

Update Your DEV Experience Level:


Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠