Click here to Skip to main content
15,867,771 members
Articles / Web Development / HTML
Tip/Trick

Java: How to convert RTF into HTML

Rate me:
Please Sign up or sign in to vote.
4.91/5 (9 votes)
19 Dec 2010CPOL 72.5K   7   4
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)


Written By
Software Developer 13
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionto sucessfully test this code.. Pin
lupus5117-Sep-12 6:54
lupus5117-Sep-12 6:54 
Questionhow to convert html to rtf Pin
Deepika Rani C23-Jul-12 22:57
Deepika Rani C23-Jul-12 22:57 
GeneralHow to convert HTML into RTF Pin
sovannoty29-Nov-11 0:23
sovannoty29-Nov-11 0:23 
GeneralGood Work Pin
Abdul Quader Mamun16-Dec-10 8:39
Abdul Quader Mamun16-Dec-10 8:39 
Good Work

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.