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

Andrew Wilson
1 min readJul 22, 2022

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.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>

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;
import java.io.File;
import java.io.IOException;

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

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.