Find and Highlight Text in Word in Java

This article demonstrates how to find and highlight text in a Word document using Spire.Doc for Java.

In Spire.Doc for Java, there are two methods can be used to find and highlight text in a Word document: findString() and findAllString(). The findString() method finds the first matched text, while the findAllString() method finds all of the matched text. The below example shows how to find all of the matched text using findAllString() method and then highlight the text.

import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;

import java.awt.*;

public class FindAndHightText {
    public static void main(String[] args){
        //Load Word document
        Document document = new Document("Input.docx");

        //Find all “Spire.Doc for Java” text
        TextSelection[] textSelections = document.findAllString("Spire.Doc for Java", false, true);

        //Set highlight color
        for (TextSelection selection : textSelections) {
            selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
        }

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

Output:

Find and Highlight Text in Word in Java