How do I generate RTF from Java?

試著忘記壹切 提交于 2019-12-03 03:49:28

If you could afford spending some money, you could use Aspose.Words, a professional library for creating Word and RTF documents for Java and .NET.

Christian Ullenboom

You can take a look at a new library called jRTF. It allows you to create new RTF documents and to fill RTF templates.

Have you had a look at the iText library? It's touted primarily as a PDF generator, though it can also generate RTF. I haven't had cause to use it personally, but the general feeling I get is that it's good, and the interface looks comprehensive and easy to work to in the abstract. Whether it would fit in well with your existing data model is another question.

iText supports RTF.

import com.lowagie.text.*;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.rtf.*;

import java.io.*;
import java.util.ArrayList;

public class HTMLtoRTF {
    public static void main(String[] args) throws DocumentException {
        Document document = new Document();

        try {
            Reader htmlreader = new BufferedReader((new InputStreamReader((new FileInputStream("C:\\Users\\asrikantan\\Desktop\\sample.htm")))));

            RtfWriter2 rtfWriter = RtfWriter2.getInstance(document, new FileOutputStream(("C:\\Users\\asrikantan\\Desktop\\sample12.rtf")));
            document.open();
            document.add(new Paragraph("Testing simple paragraph addition."));
            //ByteArrayOutputStream out = new ByteArrayOutputStream();

            StyleSheet styles = new StyleSheet();
            styles.loadTagStyle("body", "font", "Bitstream Vera Sans");
            ArrayList htmlParser = HTMLWorker.parseToList(htmlreader, styles);
            //fetch HTML line by line

            for (int htmlDatacntr = 0; htmlDatacntr < htmlParser.size(); htmlDatacntr++) {
                Element htmlDataElement = (Element) htmlParser.get(htmlDatacntr);
                document.add((htmlDataElement));
            }
            htmlreader.close();
            document.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!