// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.rtf.RtfWriter2;

public class HTML2RTF {
    private static Pattern re = Pattern.compile("([^<>]+)|((<[^>]+>)([^<>]+)(</[^>]+>))");
    public static void write(String html, String fnm) throws IOException, DocumentException {
        Document doc = new Document();
        RtfWriter2.getInstance(doc, new FileOutputStream(fnm));
        doc.open();
        Matcher m = re.matcher(html);
        while(m.find()) {
            if(m.group(1) != null) {
                Chunk ch = new Chunk(m.group(1));
                ch.setFont(new Font(Font.TIMES_ROMAN, 12.0f, Font.NORMAL));
                doc.add(ch);
            }
            if(m.group(4) != null) {
                if(m.group(3).toLowerCase().startsWith("<b")) {
                    Chunk ch = new Chunk(m.group(4));
                    ch.setFont(new Font(Font.TIMES_ROMAN, 12.0f, Font.BOLD));
                    doc.add(ch);
                } else if(m.group(3).toLowerCase().startsWith("<i")) {
                    Chunk ch = new Chunk(m.group(4));
                    ch.setFont(new Font(Font.TIMES_ROMAN, 12.0f, Font.ITALIC));
                    doc.add(ch);
                }
            }
        }
        doc.close();
    }
    public static void main(String[] args) throws Exception {
        write("foo <b>bar</b> bla <i>bla</i> etc.", "C:\\z.rtf");
    }
}
