DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. How To Convert HTML to PNG in Java

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.

Brian O'Neill user avatar by
Brian O'Neill
CORE ·
Dec. 21, 22 · Tutorial
Like (4)
Save
Tweet
Share
5.78K Views

Join the DZone community and get the full member experience.

Join For Free

Since 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:

  1. Your HTML String
  2. 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:

  1. 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).
  2. 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.
  3. 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:

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:

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:

Java
 
// 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.

API Apache Maven HTML Web development XML Java (programming language) CSS Gradle JavaScript Software repository

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DeveloperWeek 2023: The Enterprise Community Sharing Security Best Practices
  • How To Use Linux Containers
  • Low-Code Development: The Future of Software Development
  • Collaborative Development of New Features With Microservices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: