Tuesday, 29 June 2021

Set the paragraph spacing and character spacing for Word in Java

Expanding the spacing between the characters or paragraphs can make your text look bigger and bolder for standing out them, without increasing their size. This article will demonstrate how to set the paragraph spacing and character spacing for Word documents using Java codes.

Before running codes, we need to create a development environment and use a free third-party library called Free Spire.Doc for Java. It’s worth mentioning that we need to add a Jar file called Spire.Doc.jar of the library to IDEA. Get it from the link or reference it by using the following Maven configurations.

<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>

Using the code

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) {
//Load a Word document
Document document= new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Add a new paragraph and append the text
Paragraph para = new Paragraph(document);
TextRange textRange1 = para.appendText("Newly add a paragraph and set the paragraph spacing and character spacing");
textRange1.getCharacterFormat().setTextColor(Color.blue);
textRange1.getCharacterFormat().setFontSize(14);

//Set the spacing before and after paragraph
para.getFormat().setBeforeAutoSpacing(false);
para.getFormat().setBeforeSpacing(10);
para.getFormat().setAfterAutoSpacing(false);
para.getFormat().setAfterSpacing(10);

//Set the character spacing
for (Object object :(Iterable) para.getChildObjects())
{
if(object instanceof TextRange)
{
TextRange textRange= (TextRange) object;
textRange.getCharacterFormat().setCharacterSpacing(8f);
}
}
//Insert the paragraph
document.getSections().get(0).getParagraphs().insert(2, para);

//Save the document to file
document.saveToFile("output/SetSpacing.docx", FileFormat.Docx);
}
}

Output




No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...