1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.rtf.*;
import javax.swing.text.html.*;
import java.io.*;
public class RtfToHtml {
public static String convertRtfToHtml(final String txt) {
final RTFEditorKit rtf_edit = new RTFEditorKit();
final JTextPane jtp_rtf = new JTextPane();
final JTextPane jtp_html = new JTextPane();
final StyleContext rtf_context = new StyleContext();
final DefaultStyledDocument rtf_doc = new DefaultStyledDocument(rtf_context);
jtp_rtf.setEditorKit(rtf_edit);
jtp_rtf.setContentType("text/rtf");
jtp_html.setContentType("text/html");
try {
rtf_edit.read(new StringReader(txt),rtf_doc,0);
jtp_rtf.setDocument(rtf_doc);
jtp_html.setText(rtf_doc.getText(0,rtf_doc.getLength()));
HTMLDocument html_doc = null;
for (int i = 0; i < rtf_doc.getLength(); i++) {
AttributeSet a = rtf_doc.getCharacterElement(i).getAttributes();
AttributeSet p = rtf_doc.getParagraphElement(i).getAttributes();
String s = jtp_rtf.getText(i, 1);
jtp_html.select(i, i+1);
jtp_html.replaceSelection(s);
html_doc = (HTMLDocument)jtp_html.getDocument();
html_doc.putProperty("","");
html_doc.setCharacterAttributes(i,1,a,false);
MutableAttributeSet attr = new SimpleAttributeSet(p);
html_doc.setParagraphAttributes(i,1,attr,false);
}
StringWriter writer = new StringWriter();
final HTMLEditorKit html_edit = new HTMLEditorKit();
html_edit.write(writer,html_doc,0,html_doc.getLength());
return writer.toString();
} catch (Exception ex) {
return "Erreur rtf: " + ex.toString();
}
}
}; |
Partager