Tuesday, 22 February 2022

Find and Highlight Text in Specific Paragraphs of Word documents using Java

In the previous article, I showed you how to find all matched text in a Word document and then highlight it with color. This tutorial will demonstrate how to find all matched text in a specific paragraph of a Word document and highlight it.

DEPENDENCY

First of all, you need to get the latest version of Spire.Doc for Java from this link, and then manually add Spire.Doc.jar to your Java program. Or if you use Maven, you can easily import the JAR file by using the following codes in the 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>5.2.3</version>
</dependency>
</dependencies>

USING THE CODE

The following are detailed steps to find and highlight text in a specific paragraph of a Word document.

l  Initialize a Document object and load a Word sample document.

l  Get a specific section of the document using Document.getSections().get() method.

l  Get a specific paragraph of the section using Section.getParagraphs().get() method.

l  Find matched text in this paragraph using Document.findAllString() method.

l  Get the character format of these text using TextSelection.getAsOneRange().getCharacterFormat() method, and then set the highlight color using CharacterFormat.setHighlightColor() method.

l  Save to another file using Document.saveToFile() method.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;

import java.awt.*;

public class FindAllStringsInAParagraph {
public static void main(String[] args) {
//Load a Word sample document
Document doc = new Document("sample.docx");

//Get first section
Section section = doc.getSections().get(0);

//Get second paragraph in this section
Paragraph para = section.getParagraphs().get(1);

//Find all "Word" strings in this paragraph
TextSelection[] textSelections = para.findAllString("Word", false, true);

//Sets highlight color of all text
for (TextSelection selection : textSelections)
{
selection.getAsOneRange().getCharacterFormat().setHighlightColor(new Color(255, 15, 19));
}

//Save the document to another file
doc.saveToFile("output/FindMatchedStringsInAParagraph.docx", FileFormat.Docx_2013);
}
}





 

No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...