Web Renderer

FREEMIUM
By petadata | Updated a month ago | Business Software
Health Check

N/A

Back to All Tutorials (5)

Convert HTML to PDF by using Java

In this tutorial we will cover how to implement asynchronous approach of Web Renderer. You only need to send HTML content to SubmitPDFFromHTMLTask or SubmitImageFromHTMLTask API methods to receive task identifier as response. There is also SubmitPDFFromUrlTask and SubmitImageFromUrlTask methods to render PDF or Image from public Web Uri.

After receiving task identifier you need to check task status by calling GetRenderingTaskStatus method. You need to call same method after a few seconds delay as long as task status equals to “Waiting”. Once you receive “Completed” from GetRenderingTaskStatus method you can call DownloadResult method to download final file. We have used Apache HTTP Client libraries in this tutorial. You can add dependencies below in your pom.xml file.

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.13</version>
</dependency>

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpmime</artifactId>
     <version>4.5.13</version>
</dependency>

<dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.11.0</version>
</dependency>

You can use the Java implementation below.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class WebRenderer {
    private static String submitPDFFromHTMLTask(CloseableHttpClient httpClient, String htmlContent, String uri, String rapidApiKey) throws IOException {
        HttpPost submitPDFFromHTMLTaskPost = new HttpPost("https://web-renderer.p.rapidapi.com/SubmitPDFFromHTMLTask");
        submitPDFFromHTMLTaskPost.addHeader("X-RapidAPI-Key", rapidApiKey);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("uri", uri, ContentType.TEXT_PLAIN);
        builder.addTextBody("useCompression", "false", ContentType.TEXT_PLAIN);
        builder.addTextBody("pageLabel", "Home Page", ContentType.TEXT_PLAIN);
        builder.addTextBody("messageLabel", "Initial Capture", ContentType.TEXT_PLAIN);
        builder.addTextBody("browserHeight", "768", ContentType.TEXT_PLAIN);
        builder.addTextBody("browserWidth", "1024", ContentType.TEXT_PLAIN);
        builder.addTextBody("htmlContent", htmlContent, ContentType.TEXT_PLAIN);

        HttpEntity requestEntity = builder.build();
        submitPDFFromHTMLTaskPost.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(submitPDFFromHTMLTaskPost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw  new IOException("Cannot post rendering task");
        }

        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8");
    }

    private static String getRenderingTaskStatus(CloseableHttpClient httpClient, String taskId, String rapidApiKey) throws IOException {
        HttpGet getConversionTaskStatus = new HttpGet("https://web-renderer.p.rapidapi.com/GetRenderingTaskStatus?taskId=" + taskId);
        getConversionTaskStatus.addHeader("X-RapidAPI-Key", rapidApiKey);

        HttpResponse response = httpClient.execute(getConversionTaskStatus);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw  new IOException("Cannot get rendering task status");
        }

        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity, "UTF-8");
    }

    private static byte[] downloadResult(CloseableHttpClient httpClient, String taskId, String rapidApiKey) throws IOException {
        HttpGet downloadResult = new HttpGet("https://web-renderer.p.rapidapi.com/DownloadResult?taskId=" + taskId);
        downloadResult.addHeader("X-RapidAPI-Key", rapidApiKey);

        HttpResponse response = httpClient.execute(downloadResult);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw  new IOException("Cannot get rendered file");
        }

        HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toByteArray(responseEntity);
    }

    public static void main(String[] args) throws Exception {
        String rapidApiKey = "<YOUR RAPID API KEY HERE>";
        String htmlContent = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body><h1>Hello World!</h1></body></html>";
        String uriOfHtmlContent = "https://www.google.com?hl=en";

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String taskId = submitPDFFromHTMLTask(httpClient, htmlContent, uriOfHtmlContent, rapidApiKey);
        int retryCount = 0;
        while (retryCount < 100)
        {
            retryCount++;
            Thread.sleep(5000);
            String status = getRenderingTaskStatus(httpClient, taskId, rapidApiKey);
            if (status.equals("Completed"))
            {
                byte[] fileBytes = downloadResult(httpClient, taskId, rapidApiKey);
                File outputFile =new File("html_from_html.pdf");
                Files.write(outputFile.toPath(), fileBytes);
                break;
            }
            else if (status.equals("Waiting"))
            {
                continue;
            }
            else if (status.equals("Failed"))
            {
                throw new Exception("Cannot rendered file");
            }
            else
            {
                throw new Exception("Invalid status");
            }
        }
    }
}