Web Renderer

FREEMIUM
By petadata | Updated un mese fa | Business Software
Health Check

N/A

Back to All Tutorials (5)

Convert HTML to PDF by using C#

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. You can use the C# implementation below.

async Task<string> SubmitPDFFromHTMLTask(string htmlContent, string uri, string rapidApiKey)
{
    using (HttpClient httpClient = new HttpClient())
    {
        using (MultipartFormDataContent form = new MultipartFormDataContent())
        {
            form.Headers.Add("X-RapidAPI-Key", rapidApiKey);
            form.Add(new StringContent(uri), "uri");
            form.Add(new StringContent("false"), "useCompression");
            form.Add(new StringContent("Home Page"), "pageLabel");
            form.Add(new StringContent("Initial Capture"), "messageLabel");
            form.Add(new StringContent("768"), "browserHeight");
            form.Add(new StringContent("1024"), "browserWidth");
            form.Add(new StringContent(htmlContent), "htmlContent");
            using (var response = await httpClient.PostAsync("https://web-renderer.p.rapidapi.com/SubmitPDFFromHTMLTask", form))
            {
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
        }
    }
}

async Task<string> GetRenderingTaskStatus(string taskId, string rapidApiKey)
{
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey);

        using (var response = await httpClient.GetAsync($"https://web-renderer.p.rapidapi.com/GetRenderingTaskStatus?taskId={taskId}"))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }
    }
}

async Task<byte[]> DownloadResult(string taskId, string rapidApiKey)
{
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey);

        using (var response = await httpClient.GetAsync($"https://web-renderer.p.rapidapi.com/DownloadResult?taskId={taskId}"))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsByteArrayAsync();
        }
    }
}

var rapidApiKey = "<YOUR RAPIDAPI KEY HERE>";
var htmlContent = "<HTML CONTENT TO RENDER>";
var uriOfHtmlContent = "https://www.google.com?hl=en";
var taskId = await SubmitPDFFromHTMLTask(htmlContent, uriOfHtmlContent, rapidApiKey);
var retryCount = 0;
while (retryCount < 100)
{
    retryCount++;
    await Task.Delay(5000);
    var status = await GetRenderingTaskStatus(taskId, rapidApiKey);
    if (status == "Completed")
    {
        var fileBytes = await DownloadResult(taskId, rapidApiKey);
        await File.WriteAllBytesAsync("html_from_html.pdf", fileBytes);
        break;
    }
    else if (status == "Waiting")
    {
        continue;
    }
    else if (status == "Failed")
    {
        throw new Exception("Cannot convert file");
    }
    else
    {
        throw new Exception("Invalid status");
    }
}