How to Convert HTML Strings to PDFs using Java

Cloudmersive
2 min readJun 10, 2022

--

Converting HTML to PDF has a lot of obvious benefits, and people do it all the time. This conversion fully renders an HTML site in PDF form, making it possible to take web pages with you on the fly without internet, edit them more easily, and print them for presentation handouts. Our HTML string to PDF API offers an easy way of fully integrating this conversion as a cloud service in your application. You can easily call this API using ready-to-run code we’ve provided below in Java.

To start, install the Java SDK with Maven. Include the below reference in the pom.xml repository:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

After that, include one in the dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Just two steps left. First, include the import classes:

// 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;

Then, ensure you have the following parameters ready before including them into the code block below:

  1. Your HTML string input
  2. Your Cloudmersive API key (if you don’t have one, visit our website and register a free account)
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();
HtmlToPdfRequest input = new HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
try {
byte[] result = apiInstance.convertWebHtmlToPdf(input);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertWebApi#convertWebHtmlToPdf");
e.printStackTrace();
}

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet