1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
| 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");
}
}
|