DEV Community


Posted on

Convert HTML to Images (BMP/ JPEG/ PNG/ GIF/ Tiff) in Java

HTML files are used to display information on web pages, and sometimes you may need to convert html files to images for better store of the information. This article will share how to achieve this task in Java using a free library.

Import Dependency

Method 1: Download the free library (Free Spire.Doc for Java) and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

Sample Code

Free Spire.Doc for Java offers the Document.saveToImages() method to convert the HTML file to Images.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class HtmlToImage {
    public static void main(String[] args) throws IOException {
        //Create a Document instance
        Document document = new Document();

        //Load a sample HTML file
        document.loadFromFile("E:\\Files\\\\input.html", FileFormat.Html, XHTMLValidationType.None);

        //Save to image. You can convert HTML to BMP, JPEG, PNG, GIF, Tiff etc.
        BufferedImage image= document.saveToImages(0, ImageType.Bitmap);
        String result = "HtmlToImage.png";
        File file= new File(result);
        ImageIO.write(image, "PNG", file);
Enter fullscreen mode Exit fullscreen mode


Top comments (1)

cicirello profile image
Vincent A. Cicirello

How come you are hosting it in a Maven repository on your own server, rather than on Maven Central?