Generally speaking, the font color in Word documents is black by default. However, in order to make some special or important contents – for example, notices in instruction document – more obvious so that readers can easily pay more attention on them, we can change the black font to other colors, such as green, red, yellow.
This article will demonstrate how to change the font color of specified paragraph text in a Word document using Java codes with the help of a free third-party library called Free Spire.Doc for Java.
DEVELOPMENT
ENVIRONMENT
Before running codes, we need to
create a development environment and add a Jar file called Spire.Doc.jar to
Intellij IDEA. The jar file can be found in the “lib” folder of the free
library, and then follow the steps listed in the screenshot below.
Actually, there is another method
to add the Jar file to IDEA. Create a Maven project in IDEA, and then write
down the following codes in the pom.xml file. Finally, click the button “Import
Changes”.
<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>3.9.0</version>
</dependency>
</dependencies>
RUNNING THE CODE
Here is a Word sample document whose font color is black, and now I’ll use Java codes to change the
font color of second paragraph text to green and third paragraph text to blue.
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("C:\\Users\\Test1\\Desktop\\Sample.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 resulting document
doc.saveToFile("output/ChangeFontColor.docx", FileFormat.Docx_2013);
}
}
Output
No comments:
Post a Comment