Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Java: How to convert RTF into HTML

, 19 Dec 2010
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Arman S.
Software Developer 13
United States United States
No Biography provided

Comments and Discussions

 
Questionto sucessfully test this code.. Pinmemberlupus5117-Sep-12 6:54 
Questionhow to convert html to rtf PinmemberDeepika Rani C23-Jul-12 22:57 
GeneralHow to convert HTML into RTF Pinmembersovannoty29-Nov-11 0:23 
GeneralGood Work PinmemberAbdul Quader Mamun16-Dec-10 8:39 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 19 Dec 2010
Article Copyright 2010 by Arman S.
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid