Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Java: How to convert RTF into HTML

4.91/5 (9 votes)
19 Dec 2010CPOL 74.1K  
This small piece of code shows how one can use Java standard libs (non-third party) to convert a RTF text into HTML.
I came up with the following solution of converting a RTF text into HTML format without dealing with third party libraries (which usually not free):
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;
}

For example, if your RTF is stored in a String variable, you can use the function like this:
String rtfText = ...;
String htmlText = rtfToHtml(new StringReader(rtfText));

And if it's in a file, you can do something like this:
String htmlText = rtfToHtml(new FileReader(new File("myfile.rtf")));

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)