This code example shows how to create an image from an RTF file. It does not handle exceptions at all - that doesn't mean your code shouldn't do that, either. The GUI code is based on
this example
The code could also be used to convert HTML to an image with the help of the JavaDoc:javax.swing.text.html.HTMLEditorKit class, but be aware that that only supports HTML 3.2 and no CSS. The Java web browser component Lobo (on SourceForge?) may be a better option. For PDF-to-image conversion, check out the PDFRenderer library (on dev.java.net).
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.text.rtf.RTFEditorKit;
public class RTF2JPEG extends JFrame
{
public static void main (String args[]) throws Exception {
RTF2JPEG self = new RTF2JPEG();
self.setTitle("RTF to JPEG");
self.setSize(400, 300);
self.setBackground(Color.gray);
self.getContentPane().setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
self.getContentPane().add(topPanel, BorderLayout.CENTER);
RTFEditorKit rtf = new RTFEditorKit();
JEditorPane editor = new JEditorPane();
editor.setEditorKit(rtf);
editor.setBackground(Color.white);
JScrollPane scroller = new JScrollPane();
scroller.getViewport().add(editor);
topPanel.add(scroller, BorderLayout.CENTER);
FileInputStream fi = new FileInputStream("example.rtf");
rtf.read(fi, editor.getDocument(), 0);
self.setVisible(true);
BufferedImage bimage = new BufferedImage(400, 300, BufferedImage.TYPE_INT_RGB);
editor.paint(bimage.getGraphics());
ImageIO.write(bimage, "JPEG", new File("example.jpg"));
self.dispose();
}
}
CodeBarn CategoryCodeSamples