How to convert HTML to PDF in Java

Today we will be looking at how to get around pesky barriers put up by file formats, and not only that, but also accomplish this quickly for large groups of files. This is actually a lot easier than you might think, as I will demonstrate with just a few snippets of code and an API:

First thing’s first, we need to dynamically compile our library using Jitpack. In your Maven POM file, add two references:





Now we just need to call the function convertDocumentAutodetectToPdf and let the API do the rest.

// 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.ConvertDocumentApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth 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");ConvertDocumentApi apiInstance = new ConvertDocumentApi();File inputFile = new File("/path/to/file"); // File | Input file to perform the operation on.try {byte[] result = apiInstance.convertDocumentAutodetectToPdf(inputFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling ConvertDocumentApi#convertDocumentAutodetectToPdf");e.printStackTrace();}

Note that this function is compatible with a wide variety of commonly used document formats, including DOCX, PPTX, XLSX, and many others. There is also a more efficient, dedicated version for HTML to PDF called convertDocumentHtmlToPdf.

Image for post

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store