Convert html file to an image file using java

Hello All, Can anybody provide me with an example, how to convert html file to an image file using Java?

Thanks in advance
LVL 1
altima4uAsked:
Who is Participating?
 
Bart CremersJava ArchitectCommented:
The code below will work for simple HTML pages, as JEditorPane can only render not to complex pages. The componentToImage method can be used for any Component subclass, so if you find a better HTML renderer somewhere you can use that to get the image result.

Most components will work with just the method, but JEditorPane needs some extra magic to make sure the page is loaded before the converter method is called. That's where the PropertyChangeListener and the Thread.yield() come in.

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class Test {
    private static volatile boolean loaded;

    public static void main(String[] args) throws IOException {
        loaded = false;
        URL url = new URL("http://www.google.com");
        JEditorPane editorPane = new JEditorPane();
        editorPane.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("page")) {
                    loaded = true;
                }
            }
        });
        editorPane.setPage(url);
        while (!loaded) {
            Thread.yield();
        }

        File file = new File("out.png");

        componentToImage(editorPane, file);
    }

    public static void componentToImage(Component comp, File file) throws IOException {
        Dimension prefSize = comp.getPreferredSize();
        System.out.println("prefSize = " + prefSize);
        BufferedImage img = new BufferedImage(prefSize.width, comp.getPreferredSize().height,
                                              BufferedImage.TYPE_INT_ARGB);
        Graphics graphics = img.getGraphics();
        comp.setSize(prefSize);
        comp.paint(graphics);
        ImageIO.write(img, "png", file);
    }

}
0
 
altima4uAuthor Commented:
Thanks a lot..
i have a small question...how can i have a jpg/ jpeg file?  as my requirement is to have a jpeg file.. pls let me know
0
 
Bart CremersJava ArchitectCommented:
You can simply change the "png" in the ImageIO.write method to "jpg". ImageIO will use this parameter to define the output format.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.