mqnoy

Word.java

Feb 4th, 2021
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import com.spire.doc.Document;
  2. import com.spire.doc.FileFormat;
  3. import com.spire.doc.documents.TextSelection;
  4.  
  5. import java.awt.*;
  6. import java.io.BufferedReader;
  7. import java.io.FileReader;
  8. import java.io.IOException;
  9.  
  10. public class Word{
  11. public static void main(String[] args) {
  12.  
  13. String input = "/Users/rifky/Desktop/replaceWithText.docx";
  14. String output = "/Users/rifky/Desktop/out/replaceWithText.docx";
  15. String findText = "then";
  16. String replacementWord = "kemudian";
  17. //load Word document
  18. Document document = new Document();
  19. document.loadFromFile(input, FileFormat.Docx);
  20.  
  21. //replace the text
  22. document.replace(findText, replacementWord, false, true);
  23.  
  24. //highlight the replaced text
  25. TextSelection[] textSelections = document.findAllString(replacementWord, false, true);
  26.  
  27. //set highlight
  28. for (TextSelection selection : textSelections) {
  29. selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.WHITE);
  30. }
  31.  
  32. //save the document
  33. document.saveToFile(output,FileFormat.Docx);
  34. }
  35.  
  36. public static String readTextFromFile(String fileName) throws IOException{
  37. StringBuffer sb = new StringBuffer();
  38. BufferedReader br = new BufferedReader(new FileReader(fileName));
  39. String content = null;
  40. while ((content = br.readLine()) != null) {
  41. sb.append(content);
  42. }
  43. return sb.toString();
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment