HTML is commonly used for displaying data and information on websites, web applications, and different platforms. There are some cases when you may need to convert HTML to images like JPG, PNG, TIFF, BMP, etc since images are difficult to modify and can be accessed by anyone. This article will demonstrate how to perform the HTML to images conversion programmatically using Free Spire.Doc for Java.
DEPENDENCY
First of all, you need to get the
package of Free Spire.Doc for Java from this link, and then manually add
Spire.Doc.jar to your Java program. If you use Maven, you can type the
following codes in the pom.xml file to easily import the JAR 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.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
Convert HTML to
Image
The following steps are to convert a HTML file to an image using Free Spire.Doc for Java.
l Create
a Document instance.
l Load
a HTML sample file using Document.loadFromFile(java.lang.String
fileName,FileFormat fileFormat,XHTMLValidationType validationType) method.
l Save
the file to an image using Document.saveToImages()
method.
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 HTML sample file
document.loadFromFile("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);
}
}
No comments:
Post a Comment