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
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;

public class Test {
    private static volatile boolean loaded;

    public static void main(String[] args) throws IOException {
        loaded = false;
        URL url = new URL("");
        JEditorPane editorPane = new JEditorPane();
        editorPane.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("page")) {
                    loaded = true;
        while (!loaded) {

        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,
        Graphics graphics = img.getGraphics();
        ImageIO.write(img, "png", file);

altima4uAuthor Commented:
Thanks a lot..
i have a small can i have a jpg/ jpeg file?  as my requirement is to have a jpeg file.. pls let me know
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.
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.