Java: Convert HTML to Images

The conversion of HTML files to Image File Formats makes it easier to archive and store HTML pages because images are difficult to alter and can be viewed by virtually anyone. This article will demonstrate how to programmatically convert a HTML file to an image using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<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</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Convert HTML to Image

The following steps show you how to convert a HTML file to an image.

  • Create a Document instance.
  • Load a sample HTML file using Document.loadFromFile(java.lang.String fileName,FileFormat fileFormat,XHTMLValidationType validationType) method.
  • Save the file to Image using Document.saveToImages() method.
  • Java
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("C:\\Users\\Test1\\Desktop\\sample.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 = "output/HtmlToImage.png";
        File file= new File(result);
        ImageIO.write(image, "PNG", file);
    }
}

Java: Convert HTML to Images

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.