This article will show you how to change the text color of paragraphs in a Word document. As before, you will need a library called Spire.Doc for Java.
1. From the official website of E-iceblue Free Spire.doc for Download the free version of Java .
2. Start the IDE, create a new project, and then add the appropriate Spire.doc.jar to the reference that was in the installed file.
import java.awt.*;
public class ChangeFontColor { public static void main(String[] args){ //Create a Document object. Document doc = new Document(); //Load Word. doc.loadFromFile("FontColorExample.docx");
//Get the first section.
Section section = doc.getSections().get(0);
//Get the second paragraph in the first section.
Paragraph p1 = section.getParagraphs().get(1);
//Loop through the second paragraph.
for (int i = 0; i < p1.getChildObjects().getCount(); i ++)
{
//Change the 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);
//Loop through the third paragraph
for (int j = 0; j < p2.getChildObjects().getCount(); j ++)
{
//Change the 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);
}
}
//you save.
doc.saveToFile("ChangeFontColor.docx", FileFormat.Docx_2013);
}
}
<h4> <strong> Completion example </strong> </h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210106/20210106114855.png " alt="f:id:lendoris:20210106114855p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p> </p>
Recommended Posts