Skip to content

Commit b1fb109

Browse files
authored
Merge pull request #1 from DharaniThangarasu/Add-Find-Replace-Sample
Added example for find and replace in word document
2 parents 1fad03d + 88fb9a2 commit b1fb109

26 files changed

+802
-1
lines changed

README.md

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,68 @@
11
# Java-Word-Find-and-Replace-Examples
2-
Find and replace text in a Word document in Java without Microsoft Word or interop.
2+
3+
This repository contains examples that illustrates how to find and replace text in Word documents programmatically in Java using [Syncfusion’s Java Word library](https://www.syncfusion.com/word-framework/java/word-library?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) (Essential DocIO) without Microsoft Word or Office interop dependencies.
4+
5+
## Find and replace text in Word documents using Java
6+
7+
The Syncfusion Java Word library (Essential DocIO) provides comprehensive APIs to find and replace text in a Word document with any desired text, image, hyperlink, paragraph, table, and part of a document or an entire document. It provides options to find text by matching case and whole words. You can find each occurrence one by one or all the occurrences of a text in the document. It saves your efforts and time by helping you to automate find and replace a pattern of text in a Word document using [Regex](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex). It allows you to save the resultant document as Word document (DOCX, WordML), HTML, RTF.
8+
9+
## Jar files
10+
11+
You can download the jars from the Syncfusion [maven repository](https://jars.syncfusion.com/?_ga=2.177721445.1332356717.1617771042-23317178.1569844681) to use our artifacts in your projects. It helps you to use the Syncfusion Java packages without installing Essential Studio or platform installation to development with Syncfusion controls.
12+
13+
## Key Features
14+
15+
- [Find and highlight text in Java](findandhighlighttext/) - Find text from a Word document and format or highlight it.
16+
17+
- [Find and replace text in Java](findandreplacetext/) - Find text from a Word document and replace it with another text.
18+
19+
- [Replace text with image in Java](replacetextwithimage/) - Find a placeholder text from a Word document and replace it with any desired image.
20+
21+
- [Replace text with merge field in Java](replacetextwithmergefield/) - Find a pattern of text from a Word document and replace it with merge fields.
22+
23+
- [Replace text with table in Java](replacetextwithtable/) - Find a placeholder text from a Word document and replace it with a table.
24+
25+
- [Replace text with document in Java](replacetextwithdocument/) - Find text from a Word document and replace it with another Word document.
26+
27+
- [Find and replace several paragraphs in Java](findandreplaceseveralparagraphs/) - Find text that extends to several paragraphs in a Word document and replace it with another Word document.
28+
29+
## Screenshots
30+
31+
**Find and highlight text**
32+
33+
<p align="center">
34+
<img src="screenshots/Find-and-highlight-text.png" alt="Find text from a Word document and format or highlight it in Java"/>
35+
</p>
36+
37+
**Find and replace text**
38+
39+
<p align="center">
40+
<img src="screenshots/Replace-misspelt-word.png" alt="Find a misspelt word from a Word document and replace it with desired word in Java"/>
41+
</p>
42+
43+
**Replace text with table**
44+
45+
<p align="center">
46+
<img src="screenshots/Replace-text-with-table.png" alt="Find text from a Word document and replace it with a table in Java"/>
47+
</p>
48+
49+
# Resources
50+
51+
- **Product page:** [Syncfusion Java Word Framework](https://www.syncfusion.com/word-framework/java?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples)
52+
53+
- **Documentation:** [Find and Replace using Syncfusion Java Word library](https://help.syncfusion.com/java-file-formats/word-library/working-with-find-and-replace)
54+
55+
- **Online demo:** [Essential DocIO demos](https://github.com/syncfusion/java-demos?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples)
56+
57+
- **Download:** [Syncfusion File Formats Controls](https://www.syncfusion.com/sales/products/fileformats?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples)
58+
59+
# Support and feedback
60+
61+
* For queries, contact our [Syncfusion support team](https://www.syncfusion.com/support/directtrac/incidents/newincident?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) or post the queries through [community forums](https://www.syncfusion.com/forums?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples).
62+
63+
* To renew the subscription, click [here](https://www.syncfusion.com/sales/products?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) or contact our sales team at [salessupport@syncfusion.com](mailto:salessupport@syncfusion.com).
64+
65+
# License
66+
67+
This is a commercial product and requires a paid license for possession or use. Syncfusion’s licensed software, including this component, is subject to the terms and conditions of [Syncfusion's EULA](https://www.syncfusion.com/eula/es?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples). You can purchase a license [here](https://www.syncfusion.com/sales/products?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples) or start a free 30-day trial [here](https://www.syncfusion.com/account/manage-trials/start-trials?utm_source=github&utm_medium=listing&utm_campaign=java-create-word-examples).
68+
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.io.*;
2+
import com.syncfusion.docio.*;
3+
import com.syncfusion.javahelper.system.drawing.ColorSupport;
4+
5+
public class FindAndHighlightText {
6+
7+
public static void main(String[] args) throws Exception {
8+
// Opens the input Word document.
9+
WordDocument document = new WordDocument(getDataDir("FindAndHighlightText_Template.docx"), FormatType.Docx);
10+
// Finds all occurrence of the text in the Word document.
11+
TextSelection[] textSelections = document.findAll("Adventure", true, true);
12+
for (int i = 0; i < textSelections.length; i++) {
13+
// Sets the highlight color for the searched text as Yellow.
14+
textSelections[(int) i].getAsOneRange().getCharacterFormat().setHighlightColor(ColorSupport.getYellow());
15+
}
16+
// Saves the Word document
17+
document.save("Result.docx");
18+
// Closes the document
19+
document.close();
20+
}
21+
22+
/**
23+
* Get the file path
24+
*
25+
* @param path specifies the file path
26+
*/
27+
private static String getDataDir(String path) {
28+
File dir = new File(System.getProperty("user.dir"));
29+
if (!(dir.toString().endsWith("Java-Word-Find-and-Replace-Examples")))
30+
dir = dir.getParentFile();
31+
dir = new File(dir, "resources");
32+
dir = new File(dir, path);
33+
if (dir.isDirectory() == false)
34+
dir.mkdir();
35+
return dir.toString();
36+
}
37+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.io.*;
2+
import com.syncfusion.docio.*;
3+
4+
public class FindAndReplaceSeveralParagraphs {
5+
6+
public static void main(String[] args) throws Exception {
7+
// Opens the input Word document.
8+
WordDocument document = new WordDocument(getDataDir("FindAndReplaceSeveralParagraphs_Template.docx"),
9+
FormatType.Docx);
10+
WordDocument subDocument = new WordDocument(getDataDir("Source.docx"), FormatType.Docx);
11+
// Gets the content from another Word document to replace.
12+
TextBodyPart replacePart = new TextBodyPart(subDocument);
13+
for (Object bodyItem_tempObj : subDocument.getLastSection().getBody().getChildEntities()) {
14+
TextBodyItem bodyItem = (TextBodyItem) bodyItem_tempObj;
15+
replacePart.getBodyItems().add(bodyItem.clone());
16+
}
17+
String placeholderText = "Suppliers/Vendors of Northwind" + "Customers of Northwind"
18+
+ "Employee details of Northwind traders" + "The product information" + "The inventory details"
19+
+ "The shippers" + "Purchase Order transactions" + "Sales Order transaction" + "Inventory transactions"
20+
+ "Invoices" + "[end replace]";
21+
// Finds the text that extends to several paragraphs and replaces it with
22+
// desired content.
23+
document.replaceSingleLine(placeholderText, replacePart, false, false);
24+
subDocument.close();
25+
// Saves the Word document
26+
document.save("Result.docx");
27+
// Closes the document
28+
document.close();
29+
}
30+
31+
/**
32+
* Get the file path
33+
*
34+
* @param path specifies the file path
35+
*/
36+
private static String getDataDir(String path) {
37+
File dir = new File(System.getProperty("user.dir"));
38+
if (!(dir.toString().endsWith("Java-Word-Find-and-Replace-Examples")))
39+
dir = dir.getParentFile();
40+
dir = new File(dir, "resources");
41+
dir = new File(dir, path);
42+
if (dir.isDirectory() == false)
43+
dir.mkdir();
44+
return dir.toString();
45+
}
46+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.io.File;
2+
import com.syncfusion.docio.*;
3+
4+
public class FindAndReplaceText {
5+
6+
public static void main(String[] args) throws Exception {
7+
// Opens the input Word document.
8+
WordDocument document = new WordDocument(getDataDir("FindAndReplaceText_Template.docx"));
9+
// Finds all occurrences of a misspelled word and replaces with properly spelled word.
10+
document.replace("Cyles", "Cycles", true, true);
11+
// Saves the resultant file in the given path.
12+
document.save("Result.docx");
13+
document.close();
14+
}
15+
16+
/**
17+
* Get the file path
18+
*
19+
* @param path specifies the file path
20+
*/
21+
private static String getDataDir(String path) {
22+
File dir = new File(System.getProperty("user.dir"));
23+
if (!(dir.toString().endsWith("Java-Word-Find-and-Replace-Examples")))
24+
dir = dir.getParentFile();
25+
dir = new File(dir, "resources");
26+
dir = new File(dir, path);
27+
if (dir.isDirectory() == false)
28+
dir.mkdir();
29+
return dir.toString();
30+
}
31+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.io.*;
2+
import java.util.regex.Pattern;
3+
import com.syncfusion.docio.*;
4+
import com.syncfusion.javahelper.system.*;
5+
import com.syncfusion.javahelper.system.text.regularExpressions.MatchSupport;
6+
7+
public class ReplaceTextWithDocument {
8+
9+
public static void main(String[] args) throws Exception {
10+
// Opens the Word template document
11+
WordDocument document = new WordDocument(getDataDir("ReplaceTextWithDocument_Template.docx"), FormatType.Docx);
12+
TextSelection[] textSelections = document.findAll(Pattern.compile(MatchSupport.trimPattern("\\[(.*)\\]")));
13+
for (int i = 0; i < textSelections.length; i++) {
14+
WordDocument subDocument = new WordDocument(getDataDir(
15+
StringSupport.trimEnd(StringSupport.trimStart(textSelections[i].getSelectedText(), '['), ']')
16+
+ ".docx"),
17+
FormatType.Docx);
18+
document.replace(textSelections[(int) i].getSelectedText(), subDocument, true, true);
19+
subDocument.close();
20+
}
21+
// Saves the Word document
22+
document.save("Result.docx");
23+
// Closes the document
24+
document.close();
25+
}
26+
27+
/**
28+
* Get the file path
29+
*
30+
* @param path specifies the file path
31+
*/
32+
private static String getDataDir(String path) {
33+
File dir = new File(System.getProperty("user.dir"));
34+
if (!(dir.toString().endsWith("Java-Word-Find-and-Replace-Examples")))
35+
dir = dir.getParentFile();
36+
dir = new File(dir, "resources");
37+
dir = new File(dir, path);
38+
if (dir.isDirectory() == false)
39+
dir.mkdir();
40+
return dir.toString();
41+
}
42+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import java.io.*;
2+
import java.util.regex.*;
3+
import com.syncfusion.docio.*;
4+
import com.syncfusion.javahelper.system.text.regularExpressions.MatchSupport;
5+
6+
public class ReplaceTextWithImage {
7+
8+
public static void main(String[] args) throws Exception {
9+
//Opens the input Word document.
10+
WordDocument document = new WordDocument(getDataDir("FindAndReplaceImage_Template.docx"));
11+
//Finds all the image placeholder text in the Word document.
12+
TextSelection[] textSelections = document.findAll(Pattern.compile(MatchSupport.trimPattern("^//(.*)")));
13+
for (int i = 0; i < textSelections.length; i++) {
14+
// Replaces the image placeholder text with desired image.
15+
WParagraph paragraph = new WParagraph(document);
16+
WPicture picture = (WPicture) paragraph
17+
.appendPicture(new FileInputStream(getDataDir(textSelections[i].getSelectedText() + ".png")));
18+
TextSelection newSelection = new TextSelection(paragraph, 0, 1);
19+
TextBodyPart bodyPart = new TextBodyPart(document);
20+
bodyPart.getBodyItems().add(paragraph);
21+
document.replace(textSelections[i].getSelectedText(), bodyPart, true, true);
22+
}
23+
//Saves the resultant file in the given path.
24+
document.save("Result.docx");
25+
document.close();
26+
27+
}
28+
29+
/**
30+
* Get the file path
31+
*
32+
* @param path specifies the file path
33+
*/
34+
private static String getDataDir(String path) {
35+
File dir = new File(System.getProperty("user.dir"));
36+
if (!(dir.toString().endsWith("Java-Word-Find-and-Replace-Examples")))
37+
dir = dir.getParentFile();
38+
dir = new File(dir, "resources");
39+
dir = new File(dir, path);
40+
if (dir.isDirectory() == false)
41+
dir.mkdir();
42+
return dir.toString();
43+
}
44+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.io.*;
2+
import java.util.regex.Pattern;
3+
import com.syncfusion.docio.*;
4+
import com.syncfusion.javahelper.system.*;
5+
import com.syncfusion.javahelper.system.text.regularExpressions.MatchSupport;
6+
7+
public class ReplaceTextWithMergeField {
8+
9+
public static void main(String[] args) throws Exception {
10+
// Opens the input Word document.
11+
WordDocument document = new WordDocument(getDataDir("ReplaceWithMergeFileds_Template.docx"));
12+
// Finds all the placeholder text enclosed within '«' and '»' in the Word document.
13+
TextSelection[] textSelections = document.findAll(
14+
Pattern.compile(MatchSupport.trimPattern("«([(?i)image(?-i)]*:*[a-zA-Z0-9 ]*:*[a-zA-Z0-9 ]+)»")));
15+
String[] searchedPlaceholders = new String[textSelections.length];
16+
for (int i = 0; i < textSelections.length; i++) {
17+
searchedPlaceholders[(int) i] = textSelections[(int) i].getSelectedText();
18+
}
19+
for (int i = 0; i < searchedPlaceholders.length; i++) {
20+
WParagraph paragraph = new WParagraph(document);
21+
// Replaces the placeholder text enclosed within '«' and '»' with desired merge field.
22+
paragraph.appendField(
23+
StringSupport.trimEnd(StringSupport.trimStart(searchedPlaceholders[i], '«'), '»'),
24+
FieldType.FieldMergeField);
25+
TextSelection newSelection = new TextSelection(paragraph, 0, paragraph.getItems().getCount());
26+
TextBodyPart bodyPart = new TextBodyPart(document);
27+
bodyPart.getBodyItems().add(paragraph);
28+
document.replace(searchedPlaceholders[(int) i], bodyPart, true, true, true);
29+
}
30+
// Saves the resultant file in the given path.
31+
document.save("Result.docx");
32+
document.close();
33+
}
34+
35+
/**
36+
* Get the file path
37+
*
38+
* @param path specifies the file path
39+
*/
40+
private static String getDataDir(String path) {
41+
File dir = new File(System.getProperty("user.dir"));
42+
if (!(dir.toString().endsWith("Java-Word-Find-and-Replace-Examples")))
43+
dir = dir.getParentFile();
44+
dir = new File(dir, "resources");
45+
dir = new File(dir, path);
46+
if (dir.isDirectory() == false)
47+
dir.mkdir();
48+
return dir.toString();
49+
}
50+
}

0 commit comments

Comments
 (0)