When manipulating Word documents, it's inevitably that we will use the search function if we want to find the specific text quickly. And in order to facilitate ourselves or others to notice it, we can highlight the specific text with background color. In this article,I will introduce how to use Free Spire.Doc for Java to realize the function of finding and highlighting text in Word in Java application.
Installation
First of all, you need to download the latest Free Spire.Doc for Java and unzip it. Then you need to add Spire.Doc.jar to your project as dependency.
If you use maven, you can refer to this article
https://www.e-iceblue.com/Tutorials/Licensing/How-to-install-Spire.PDF-for-Java-from-Maven-Repository.html
Find and Highlight Text
We can use the findAllString() method to find all of the matched text in the Word document and then highlight them. Here’s an example of it:
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 “Nicholas” text
TextSelection[] textSelections = document.findAllString("Nicholas", 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);
}
}
Top comments (0)