Java Swing HTML rtfToBody(String rtf)

Here you can find the source of rtfToBody(String rtf)

Description

rtf To Body

License

Open Source License

Declaration

public static String rtfToBody(String rtf) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import java.util.regex.Pattern;
import javax.swing.JEditorPane;
import javax.swing.text.BadLocationException;

import javax.swing.text.EditorKit;

public class Main {
    private static final Pattern BODY_PATTERN = Pattern.compile(".*<body.*?>(.*)</body>.*",
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    public static String rtfToBody(String rtf) throws IOException {
        String html = rtfToHtml(new StringReader(rtf));
        if (html.contains("<body")) {
            html = BODY_PATTERN.matcher(html).replaceAll("$1");
        }/*from  www  .  java2s . com*/
        return html;
    }

    public static String rtfToHtml(String rtf) throws IOException {
        return rtfToHtml(new StringReader(rtf));
    }

    /**
     * @see http 
     *      ://www.codeproject.com/Tips/136483/Java-How-to-convert-RTF-into-HTML
     * @param rtf
     * @return
     * @throws IOException
     */
    public static String rtfToHtml(Reader rtf) throws IOException {
        JEditorPane p = new JEditorPane();
        p.setContentType("text/rtf");
        EditorKit kitRtf = p.getEditorKitForContentType("text/rtf");
        try {
            kitRtf.read(rtf, p.getDocument(), 0);
            kitRtf = null;
            EditorKit kitHtml = p.getEditorKitForContentType("text/html");
            Writer writer = new StringWriter();
            kitHtml.write(writer, p.getDocument(), 0, p.getDocument().getLength());
            return writer.toString();
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. isUnderline(Element element)
  2. loadStyleSheet(URL url)
  3. makeStyleSheet(String name)
  4. nameOf(Element element)
  5. plainToHtml(String plain)
  6. rtfToHtml(Reader rtf)
  7. rtfToHtml(String rtf)
  8. stripHTML(String html)
  9. toBold(final T label)