JavaRanch Home    
 
This page:         last edited 01 November 2012         What's Changed?         Edit

RTF2Image   

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 may be a better option. For PDF-to-image conversion, check out the PDFRenderer library.


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 {
        // Create an instance of the application
        RTF2JPEG self = new RTF2JPEG();
        self.setTitle("RTF to JPEG");
        self.setSize(400300);
        self.setBackground(Color.gray);
        self.getContentPane().setLayout(new BorderLayout());

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        self.getContentPane().add(topPanel, BorderLayout.CENTER);

        // Create an RTF editor window
        RTFEditorKit rtf = new RTFEditorKit();
        JEditorPane editor = new JEditorPane();
        editor.setEditorKit(rtf);
        editor.setBackground(Color.white);

        // This text could be big so add a scroll pane
        JScrollPane scroller = new JScrollPane();
        scroller.getViewport().add(editor);
        topPanel.add(scroller, BorderLayout.CENTER);

        // Load an RTF file into the editor
        FileInputStream fi = new FileInputStream("example.rtf");
        rtf.read(fi, editor.getDocument(), 0);

        self.setVisible(true);

        // create an image and render the document into it
        BufferedImage bimage = new BufferedImage(400300BufferedImage.TYPE_INT_RGB);
        editor.paint(bimage.getGraphics());

        // other possible image formats are PNG, BMP, GIF (starting with Java 6),
        // and TIFF (using the JAI ImageIO library)
        ImageIO.write(bimage, "JPEG"new File("example.jpg"));

        self.dispose();
    }
}


CodeBarn CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton