Change Font in Word using Java

·

2 min read

Changing the font of text in MS Word is fairly simple and can be done in just a few easy steps. This article focuses on how to change the text font of an existing Word document in Java using a free Java library.

Install the Library (Two Methods)

Method 1: Download the free library(Free Spire.Doc for Java) 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>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
   </repository>
</repositories>
<dependencies>
   <dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.doc.free</artifactId>
      <version>5.2.0</version>
   </dependency>
</dependencies>

Sample Code

Free Spire.Doc for Java offers the CharacterFormat.setFontName() and CharacterFormat.setFontSize() methods to set a specified font and size, and you can apply them to existing text in the document using TextRange.applyCharacterFormat() method. The following is the complete sample code.

import com.spire.doc.*;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;
import com.spire.doc.formatting.CharacterFormat;

public class setFont {
    public static void main(String[] args) {

        Document doc = new Document();
        doc.loadFromFile("test.docx");

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

        //Get the paragraph
        Paragraph p = s.getParagraphs().get(0);

        //Create a characterFormat object
        CharacterFormat format = new CharacterFormat(doc);
        //Set font
        format.setFontName("Arial");
        format.setFontSize(16);

        //Loop through the childObjects of paragraph
        for (int j = 0; j < p.getChildObjects().getCount(); j ++)
        {
            if ( p.getChildObjects().get(j) instanceof TextRange)
            {
                TextRange tr = (TextRange) p.getChildObjects().get(j);
                //Apply character format
                tr.applyCharacterFormat(format);
            }
        }

        doc.saveToFile("setFont.docx", FileFormat.Docx);
    }
}