The “Highlight” function in Microsoft Word enables you to add a bright background color to specific words or phrases. This is very useful when you want to emphasize important information in a Word document. In addition to highlighting text, Microsoft Word also allows you to find highlighted text through the “Find” function. In this article, I will explain how to programmatically highlight text or get highlighted text in Word documents in Java using Free Spire.Doc for Java library.
- Highlight The First Occurrence of a Specific Text in a Word Document
- Highlight All Occurrences of a Specific Text in a Word Document
- Get Highlighted Text in a Word Document
Add Dependencies
Method 1: If you are using maven, you can easily import the JAR file of Free Spire.Doc for Java into your application by adding the following code to your project’s pom.xml file.
<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>
Method 2: If you are not using maven, you can download Spire.Doc for Java from this link, extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.
Highlight The First Occurrence of a Specific Text in a Word Document using Java
The following steps demonstrate how to highlight the first occurrence of a specific text in a Word document:
- Initialize an instance of the Document class.
- Load a Word document using Document.loadFromFile() method.
- Find the first occurrence of a specific text using Document.findString() method.
- Get the found text as a single text range using TextSelection.getAsOneRange() method.
- Set a highlight color for the text range using TextRange.getCharacterFormat().setHighlightColor() method.
- Save the result document using Document.saveToFile() method.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange;
import java.awt.*;
public class HighlightText {
public static void main(String []args){
//Create a Document instance
Document document = new Document();
//Load a Word document
document.loadFromFile("Input1.docx");
//Find the first occurrence of a specific text
TextSelection seletion = document.findString("World Cup", false, true);
//Get the found text as a single text range
TextRange textRange = seletion.getAsOneRange();
//Set a highlight color
textRange.getCharacterFormat().setHighlightColor(Color.YELLOW);
//Save the result document
document.saveToFile("HighlightText.docx", FileFormat.Docx_2013);
}
}
Highlight All Occurrences of a Specific Text in a Word Document using Java
The following steps demonstrate how to highlight all the occurrences of a specific text in a Word document:
- Initialize an instance of the Document class.
- Load a Word document using Document.loadFromFile() method.
- Find all the occurrences of a specific text using Document.findAllString() method.
- Iterate through the found text.
- Get each text as a single text range using TextSelection.getAsOneRange() method.
- Set a highlight color for the text range using TextRange.getCharacterFormat().setHighlightColor() method.
- Save the result document using Document.saveToFile() method.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange;
import java.awt.*;
public class HighlightAllMatchedText {
public static void main(String []args){
//Create a Document instance
Document document = new Document();
//Load a Word document
document.loadFromFile("Input1.docx");
//Find all occurrences of a specific text
TextSelection[] text = document.findAllString("World Cup", false, true);
//Iterate through the found text
for(TextSelection selection : text){
//Get each text as a single text range
TextRange textRange = selection.getAsOneRange();
//Set a highlight color
textRange.getCharacterFormat().setHighlightColor(Color.YELLOW);
}
//Save the result document
document.saveToFile("HighlightAllMatchedText.docx", FileFormat.Docx_2013);
}
}
Get Highlighted Text in a Word Document using Java
The following steps demonstrate how to get all the text highlighted with a specific color in a Word document:
- Initialize an instance of the Document class.
- Load a Word document using Document.loadFromFile() method.
- Initialize an instance of the StringBuilder class.
- Iterate through all sections in the document.
- Iterate through all paragraphs in each section.
- Iterate through all child objects in each paragraph.
- Check if the current child object is of TextRange type.
- If the result is true, typecast the child object as TextRange.
- Find the text range highlighted with a specific color using TextRange.getCharacterFormat().getHighlightColor() method.
- Get the text through TextRange.Text property and then add it to the StringBuilder.
- Write the text in the StringBuilder into a text file.
import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;
import java.awt.*;
import java.io.FileWriter;
import java.io.IOException;
public class GetHighlightedText {
public static void main(String []args) {
//Create a Document instance
Document document = new Document();
//Load a Word document
document.loadFromFile("Input2.docx");
StringBuilder sb = new StringBuilder();
//Loop through all sections in the document
for(Section section :(Iterable<Section>) document.getSections()){
//Loop through all paragraphs in each section
for(Paragraph paragraph : (Iterable<Paragraph>) section.getBody().getParagraphs())
{
//Loop through all child objects in each paragraph
for(DocumentObject obj : (Iterable<DocumentObject>) paragraph.getChildObjects())
{
//Check if the current child object is of TextRange type
if (obj instanceof TextRange)
{
TextRange textRange = (TextRange) obj;
//Check if the text range is highlighted with a specific color
if (textRange.getCharacterFormat().getHighlightColor().equals(Color.YELLOW)){
//Get the highlighted text
String highlightedText = textRange.getText();
sb.append(highlightedText + "\n");
}
}
}
}
}
FileWriter writer;
try {
//Save the highlighted text to a text file
writer = new FileWriter("HighlightedText.txt");
writer.write(sb.toString());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}