How To Convert HTML to PNG in Java
This article discusses the need for visual documentation of HTML code and provides a free API solution, which converts HTML strings to a PNG screenshots.
Join the DZone community and get the full member experience.
Join For FreeSince its conception in the late 1980s, HyperText Markup Language (HTML) has persisted as a critical element in displaying web pages online. This ubiquitous programming language continues to offer a detailed framework for structuring the content we see and interact with on the web, allowing us to format text and multimedia components in plain-text code, which is simple enough to change when the need arises.
The Transformation of HTML
As is the case with nearly all programming languages, HTML has transformed to incorporate dozens of new features over the decades since its introduction, accommodating typical contemporary pressures such as community feedback/critique and the rapid growth of adjacent web development technologies. The results of this transformation are easily visible to us in the output of modern HTML code; for example, the most recent HTML iteration–HTML5, introduced in 2014–offers new, simple elements for embedding video and audio files, as well as much-needed improvements in mobile display and overall mobile functionality.
Of course, new elements and display-quality improvements are not the only reason a website’s HTML code will reliably change over time. Websites are designed and redesigned constantly, likely as much for the sake of innovation as in response to trends originating from user feedback. For example, a website developed in 2014 is likely to have incorporated a variety of contemporary design trends independent of the changes introduced in HTML5 that year. In the years following that project, developers of the website will likely have found themselves reiterating at least a portion of their HTML code numerous times, all the while building towards the inevitable release of HTML6 and the eventual incorporation of its new and improved features.
Given these natural progressions in HTML development, an important question arises: How do we effectively track and document the growth of our website’s HTML code? The answer is a relatively simple one, given the inherently visual nature of HTML’s output. We can easily store iterations of our HTML websites in the form of static, two-dimensional image files–screenshots–and we can accomplish this transition programmatically with relative ease.
HTML Screenshots
Capturing an HTML screenshot has a multitude of practical business applications. When new HTML code is written for a website, rendering an image of that HTML code’s output works as a simple, easily shareable “status check” for how its content appears on a web browser at a given point in time. By the same token, such screenshots offer an excellent method for rapidly testing new, experimental iterations of HTML code, making it simple for a developer to create and store various versions–both successful and unsuccessful–of a project in development. Screenshots additionally provide an ideal means of visual documentation for the inevitable issues that occur with live websites, making it easier to keep track of nagging issues and track how they appear on different devices, browsers, or operating systems. With new HTML versions always looming on the horizon, all pre-existing screenshots provide a practical method of comparison with the output of older HTML versions, helping developers to advocate–among technical and non-technical audiences alike–for the incorporation of various new features, and subsequently justify the business expense that comes with those endeavors.
Tutorial
The purpose of this tutorial is to provide a simple, free, easy-to-use API solution for converting HTML strings to PNG screenshots in Java. This API will render a website fully, returning a screenshot of what the HTML displays in a regular web browser view. It supports all modern, advanced web development features, including those pertaining to HTML5, CSS, JavaScript, and more. For your convenience, ready-to-run Java code examples are supplied further down the page to help you structure your API call with ease.
This API has two mandatory request parameters, which include the following:
- Your HTML String
- A free-tier Cloudmersive API key (you can get one by visiting our website and registering a free account).
In addition to the mandatory inputs above, this API provides several optional parameters, which allow for further customization of your input request. These optional parameters include the following:
- Extra loading wait: the additional number of milliseconds to wait once the web page has finished loading before taking the screenshot (can be helpful for very asynchronous websites).
- Screenshot height: the desired height of your screenshot, expressed in terms of pixels (defaults to 1280 x 1024). Supplying the integer “0” triggers the default setting, while supplying the integer “-1” asks the API to measure and attempt a screen-height screenshot.
- Screenshot width: the desired width of your screenshot, expressed in terms of pixels (also defaults to a standard 1280 x 1024 measurement). Supplying the integers “0” or “-1” result in the same outcomes as described in the “Screenshot height” parameter above.
In its response, this API will provide a string containing the encoding for your new PNG file.
To structure your API call in Java, your first step is to install the SDK. This can be accomplished with Maven by first adding the following reference to the repository in pom.xml
:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Following that, add the reference below to the dependency in pom.xml
:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>
To install the SDK with Gradle instead, add your reference in the root build.gradle
(at the end of repositories):
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
And then add the dependency in build.gradle
:
dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v4.25'
}
With the installation complete, all that’s left is to copy and paste the following code examples and fulfill the mandatory and optional request parameters as described above:
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.ConvertWebApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
ConvertWebApi apiInstance = new ConvertWebApi();
HtmlToPngRequest input = new HtmlToPngRequest(); // HtmlToPngRequest | HTML to PNG request parameters
try {
byte[] result = apiInstance.convertWebHtmlToPng(input);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertWebApi#convertWebHtmlToPng");
e.printStackTrace();
}
Once you complete this step, you’re all done–you can now call this API and easily render HTML strings as PNG screenshots.
Note: your free-tier API key will supply a limit of 800 API calls per month with no commitments. Once you reach that limit, your total will simply reset the following month.
Opinions expressed by DZone contributors are their own.
Comments