Example usage for javax.swing.text.html HTMLEditorKit.ParserCallback HTMLEditorKit.ParserCallback

List of usage examples for javax.swing.text.html HTMLEditorKit.ParserCallback HTMLEditorKit.ParserCallback

Introduction

In this page you can find the example usage for javax.swing.text.html HTMLEditorKit.ParserCallback HTMLEditorKit.ParserCallback.

Prototype

HTMLEditorKit.ParserCallback

Source Link

Usage

From source file:net.fenyo.mail4hotspot.tools.GenericTools.java

public static String html2Text(final String html) {
    try {//from   w w  w . ja v  a 2s .  co m
        final StringBuilder sb = new StringBuilder();
        HTMLEditorKit.ParserCallback parserCallback = new HTMLEditorKit.ParserCallback() {
            private boolean readyForNewline = false;
            private boolean headParsed = false; // viter l'entte (notamment titre et styles ventuels)

            @Override
            public void handleText(final char[] data, final int pos) {
                if (headParsed) {
                    sb.append(new String(data).trim());
                    readyForNewline = true;
                }
            }

            @Override
            public void handleStartTag(final HTML.Tag t, final MutableAttributeSet a, final int pos) {
                if (readyForNewline && (t == HTML.Tag.DIV || t == HTML.Tag.BR || t == HTML.Tag.P)) {
                    sb.append("\n");
                    readyForNewline = false;
                }
            }

            @Override
            public void handleEndTag(final HTML.Tag t, final int pos) {
                if (t == HTML.Tag.HEAD)
                    headParsed = true;
            }

            @Override
            public void handleSimpleTag(final HTML.Tag t, final MutableAttributeSet a, final int pos) {
                handleStartTag(t, a, pos);
            }
        };

        // dernier paramtre true, pour viter une exception ChangedCharSetException dans le cas o le charset est redfini au dbut du HTML par un lment du style <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        new ParserDelegator().parse(new StringReader(html), parserCallback, true);
        return sb.toString();
    } catch (final IOException ex) {
        log.error(ex);
        return null;
    }
}