Java: Find and Highlight Text in Word
In daily work, if we want to highlight the key points, then highlight text is a good choice. Highlighted text is emphasized from a color perspective, making it easier to read for yourself or others. So today I will show you how to find and highlight text in a Word document through code in a Java program. The following are the ideas and steps I have organized, and the Java code is attached for your reference.
Programming
Environment
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>
<url>https://repo.e-iceblue.com/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
Specific Steps:
- Create a Word document and load it using Document.loadFromFile() method.
- Find all the text you need to highlight using Document.findAllString()method.
- Set highlight color using TextSelection.getAsOneRange().getCharacterFormat().setHighlightColor()method.
- Save the file using Document.saveToFile()method.
FULL CODE:
[Java]
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("Sample1.docx");
//Find all “United Kingdom” text
TextSelection[] textSelections = document.findAllString("United Kingdom", 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);
}
}
Effective Shot:
Conclusion:
In this post, you have learned how to find and highlight text in Word in Java. Not only that, we also have other functions, such as,Extract Text and Images from Word in Java, Replace Text with Image in Word in Java , Replace Text with New Text in Word in Java and so on. Apart from that, if you'd like to learn more, you can visit the Spire.Doc Program Guide Content for Java to explore more about for Spire.Doc for Java.
Comments
Post a Comment