|
9 | 9 |
|
10 | 10 | public class HTML { |
11 | 11 |
|
| 12 | + public static final boolean debug = false; |
| 13 | + |
12 | 14 | /** Generate html.form.input |
13 | 15 | * @param name = element name (optional) |
14 | 16 | * @param id = element id (optional) |
@@ -143,4 +145,45 @@ public static String addJSfile(String file) { |
143 | 145 | public static String addJSinline(String script) { |
144 | 146 | return "<script>" + script + "</script>"; |
145 | 147 | } |
| 148 | + |
| 149 | + /** Converts HTML to text/plain. */ |
| 150 | + public static String toText(String html) { |
| 151 | + StringBuilder txt = new StringBuilder(); |
| 152 | + int html_len = html.length(); |
| 153 | + if (debug) JFLog.log("len=" + html_len); |
| 154 | + int html_off = 0; |
| 155 | + while (html_off < html_len) { |
| 156 | + int i1 = html.indexOf('<', html_off); |
| 157 | + if (debug) JFLog.log("i1=" + i1); |
| 158 | + if (i1 == -1) { |
| 159 | + txt.append(html.substring(html_off, html_len - html_off)); |
| 160 | + html_off = html_len; |
| 161 | + } else { |
| 162 | + if (i1 > 0) { |
| 163 | + if (debug) JFLog.log("substring=" + html_off + "," + i1); |
| 164 | + txt.append(html.substring(html_off, i1)); |
| 165 | + } |
| 166 | + int i2 = html.indexOf('>', i1); |
| 167 | + if (debug) JFLog.log("i2=" + i2); |
| 168 | + if (i2 == -1) { |
| 169 | + JFLog.log("HTML.toText() : tag left open"); |
| 170 | + break; |
| 171 | + } else { |
| 172 | + String tag = html.substring(i1 + 1, i2); |
| 173 | + switch (tag) { |
| 174 | + case "br": txt.append("\r\n"); break; |
| 175 | + } |
| 176 | + html_off = i2 + 1; |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | + return txt.toString(); |
| 181 | + } |
| 182 | + |
| 183 | + public static void main(String[] args) { |
| 184 | + String html = "<h1>This is HTML</h1><br>Converted to text!<br>"; |
| 185 | + System.out.println(html); |
| 186 | + String txt = toText(html); |
| 187 | + System.out.println(txt); |
| 188 | + } |
146 | 189 | } |
0 commit comments