0

Suppose I have a String like this.

String s = "I have this simple string java, I want to find keywords in this string";

Meantime I have a list of Keywords like this.

ArrayList<String> keywords = new ArrayList<>( Arrays.asList("string", "keywords"));

What I want to achieve is find out words in the s from keywords and generate a new string with highlighted keywords.like

String sNew = "I have this simple string java, I want to find keywords in this string";

This highlighting part is done through iText while generating a pdf.

Thanks.

D.Anush
  • 147
  • 6
  • 15
  • please show how a iText is generated and how you put bold words – azro May 26 '22 at 07:26
  • Have you tried to split your string `s` using a pattern composed from your `keywords`, i.e. something like `Pattern.compile("(string|keywords)")`? However, as you also need to extract the keyword, matching the entire input string `s` against a pattern is probably a better appriach. – Manfred May 26 '22 at 07:27
  • I cannot get the code because it is in vds. I will tell the approach. I split string to a arraylist and iterate keywords and check arraylist.contains. if, contains find, do the styling to that word and added to a string, problem is, generated string append string according to keyword list size. – D.Anush May 26 '22 at 07:32

1 Answers1

1

Based from https://stackoverflow.com/a/27081059/7212686, add Chunk with custom font

public static final Font BLACK_NORMAL = new Font(FontFamily.HELVETICA, 12, Font.NORMAL);
public static final Font BLACK_BOLD = new Font(FontFamily.HELVETICA, 12, Font.BOLD);

String s = "I have this simple string java, I want to find keywords in this string";
List<String> keywords = Arrays.asList("string", "keywords");

Paragraph p = new Paragraph();
for (String word : s.split("\\s+")) {
    if (keywords.contains(word))
        p.add(new Chunk(word, BLACK_BOLD));
    else
        p.add(new Chunk(word, BLACK_NORMAL));
    
    p.add(new Chunk(" ", BLACK_NORMAL));
}
azro
  • 53,056
  • 7
  • 34
  • 70