65.9K
CodeProject is changing. Read more.
Home

Java: How to convert RTF into HTML

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.91/5 (9 votes)

Dec 14, 2010

CPOL
viewsIcon

74152

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")));