Thanks to all the Available Libraries out there (Like Flying Saucer), That make Converting HTML Documents to images easy.
Let's explore All the Different Ways How to convert HTML to an image in Java.
There are so many Libraries available inside Java that can be used, and I'll cover Most of them in this article.
Flying Saucer is a pure Java library that we can use for Converting HTML Documents to Images.
Where Flying Saucer Library includes rendering arbitrary XML using CSS for layout and formatting.
Flying Saucer Library can Convert HTML Documents to Swing panels, PDFs, and Images.
In order to use Flying Saucer in your Java Project, you will need to add it as a Dependency through Maven or Gradle.
Build.gradle
implementation group: 'org.xhtmlrenderer', name: 'flying-saucer-core', version: '9.1.22'
pom.xml
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-core</artifactId>
<version>9.1.22</version>
</dependency>
After Integrating Flaying Saucer into your Java Project, now you can use Flaying Soucer's API to Render HTML or Convert HTML to an Image.
Just Parse your HTML Element as a Parameter and Flaying Soucer will handle the Rest.
my.java
import org.xhtmlrenderer.swing.Java2DRenderer;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class HTMLToImageConverter {
public static void main(String[] args) throws Exception {
// Your HTML Here
String htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
// Converting HTML to Image
BufferedImage image = new Java2DRenderer(htmlContent).getImage();
// Saving the Converted Image
File output = new File("output.png");
ImageIO.write(image, "png", output);
}
}
You can also use Selenium WebDriver to Convert HTML documents to an Image.
By using Selenium WebDriver can Capture a Screenshot of your HTML and Save that Screenshot.
To use Selenium WevDriver in Java, you need to Import them inside your Java Project.
After that you need to configure your Web Browser (We are going to use Chrome with Selenium).
my.java (Importing WebDrivers)
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
After Importing Selenium and Chrome WebDrivers, you need to load your HTML Content in a Browser and Capture the Screenshot and after that, you can Save that Screenshot.
my.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
public class HTMLToImageConverter {
public static void main(String[] args) throws Exception {
// Setup Chome Drivers
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Creating WebDriver instance
WebDriver driver = new ChromeDriver();
// Load HTML content in the Browser
driver.get("data:text/html,<html><body><h1>Hello, World!</h1></body></html>");
// This will Capture the Screenshot
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Storing Captured Images to file
FileUtils.copyFile(screenshot, new File("output.png"));
// Closing the WebDriver
driver.quit();
}
}
GroupDocs.Conversion Library acts as a Middleware that empowers your Java Project to convert more than 50 Document Types to Different Image formats.
my.java
//Get your AppKey from https://dashboard.groupdocs.cloud
var configuration = new Configuration("AppSID", "AppKey");
var apiInstance = new ConversionApi(configuration);
// Convert Settings
var settings = new ConvertSettings
{
FilePath = "file-to-convert.html",
Format = "jpg",
OutputPath = "ConvertedFiles"
};
// Convert to Specified Format
List response = apiInstance.ConvertDocument(new ConvertDocumentRequest(settings));
Graphics2D classes provide more refined control over geometry, coordinate modifications, color control, and text format. This is the absolute class for rendering 2D shapes, text, and images on the Java platform.
my.java
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class HtmlToImageConverter {
public static void main(String[] args) {
String htmlContent = "<h1>Hello, World!</h1>";
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setText(htmlContent);
// Set preferred
editorPane.setPreferredSize(new Dimension(800, 600));
editorPane.setSize(editorPane.getPreferredSize());
BufferedImage image = new BufferedImage(
editorPane.getWidth(), editorPane.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
// Paint
editorPane.paint(g2d);
g2d.dispose();
try {
ImageIO.write(image, "png", new File("output.png"));
System.out.println("HTML rendered successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Aspose.Words (available for Java and Python) is a class library that allows you to do a wide range of document-processing tasks.
Aspose.Words for Java Library also Provides HTML-to-image conversion capabilities.
pom.xml (Including Aspose.Words)
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>ver</version>
<classifier>jdk17</classifier>
</dependency>
my.java
import com.aspose.words.*;
Document doc = new Document("index.html");
ImageSaveOptions saveOptions = new ImageSaveOptions(output.jpg);
for (int page = 0; page < doc.getPageCount(); page++)
{
saveOptions.setPageSet(new PageSet(page));
doc.save(String.format("Output_%d.jpg", page + 1), saveOptions);
}