Change the Font Color of Paragraph Text in Word in Java

This article demonstrates how to change the font color of the text in paragraphs using Spire.Doc for Java.

The following screenshot shows the example Word document before changing font color:

Change the Font Color of Paragraph Text in Word in Java

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

import java.awt.*;

public class ChangeFontColor {
    public static void main(String[] args){
        //Create a Document instance
        Document doc = new Document();
        //Load the Word document
        doc.loadFromFile("FontColorExample.docx");

        //Get the first section and second paragraph
        Section section = doc.getSections().get(0);
        Paragraph p1 = section.getParagraphs().get(1);

        //Iterate through the childObjects of the second paragraph 
        for (int i = 0; i < p1.getChildObjects().getCount(); i ++)
        {
            //Change font color of the text in the second paragraph
            if ( p1.getChildObjects().get(i) instanceof TextRange)
            {
                TextRange tr = (TextRange) p1.getChildObjects().get(i);
                tr.getCharacterFormat().setTextColor(Color.green);
            }
        }

        //Get the third paragraph
        Paragraph p2 = section.getParagraphs().get(2);

        //Iterate through the childObjects of the third paragraph
        for (int j = 0; j < p2.getChildObjects().getCount(); j ++)
        {
            //Change font color of the text in the third paragraph
            if ( p2.getChildObjects().get(j) instanceof TextRange)
            {
                TextRange tr = (TextRange) p2.getChildObjects().get(j);
                tr.getCharacterFormat().setTextColor(Color.blue);
            }
        }
        
        //Save the resultant document
        doc.saveToFile("ChangeFontColor.docx", FileFormat.Docx_2013);
    }
}

The following screenshot shows the output Word document after changing font color:

Change the Font Color of Paragraph Text in Word in Java