Java: Find and Highlight Text in Word

The "Find" function in MS Word allows users to search for specific text or phrases in a document quickly, and users can also highlight the found text in yellow or other bright colors to make them visible to readers at a glance. In this article, you will learn how to programmatically find and highlight text in a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in 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</artifactId>
        <version>11.1.1</version>
    </dependency>
</dependencies>
    

Find and Highlight Text in Word

The detailed steps are as follows.

  • Create a Document instance
  • Load a sample Word document using Document.loadFromFile() method.
  • Find all matching text in the document using Document.findAllString(java.lang.String matchString, boolean caseSensitive, boolean wholeWord) method.
  • Loop through all matching text in the document.
  • Get the text range of a specific matching text using TextSelection.getAsOneRange() method, and then set its highlight color using TextRange.getCharacterFormat().setHighlightColor() method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;

import java.awt.*;
public class FindAndHighlight {
    public static void main(String[] args){
        //Create a Document instance
        Document document = new Document();

        //Load a sample Word document
        document.loadFromFile("E:\\Files\\input1.docx");

        //Find all matching text in the document
        TextSelection[] textSelections = document.findAllString("transcendentalism", false, true);

        //Loop through all matching text and set highlight color for them
        for (TextSelection selection : textSelections) {
            selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
        }

        //Save the document
        document.saveToFile("FindAndHighlight.docx", FileFormat.Docx_2013);
    }
}

Java: Find and Highlight Text in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.