如何使用 Go Lang 将文档转换为 PDF

在本教程中,我们将介绍如何实现文档转换套件的异步方法。您只需将源文档发送到 SubmitTIFFConversionTask 或 SubmitPDFConversionTask API 方法即可接收任务标识符作为响应。还有SubmitDOCXConversionTask方法将PDF文档转换为可编辑的Microsoft Word文档。 收到任务标识符后,您需要通过调用 GetConversionTaskStatus 方法检查任务状态。只要任务状态等于“Waiting”,您需要在几秒钟延迟后调用相同的方法。一旦您从GetConversionTaskStatus方法收到“Completed”,您可以调用DownloadResult方法来下载最终文档文件。您可以使用下面的 Go Lang 实现。 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 package main import ( "bytes" "errors" "fmt" "io" "mime/multipart" "net/http" "os" "path/filepath" "time" ) func createReqBody(filePathToConvert string, authorName string, title string, keywords string, name string) (string, io.Reader, error) { var err error buf := new(bytes.Buffer) bw := multipart.NewWriter(buf) f, err := os.Open(filePathToConvert) if err != nil { return "", nil, err } defer f.Close() authorNameField, _ := bw.CreateFormField("authorName") authorNameField.Write([]byte(authorName)) titleField, _ := bw.CreateFormField("title") titleField.Write([]byte(title)) keywordsField, _ := bw.CreateFormField("keywords") keywordsField.Write([]byte(keywords)) nameField, _ := bw.CreateFormField("name") nameField.Write([]byte(name)) _, fileName := filepath.Split(filePathToConvert) fw1, _ := bw.CreateFormFile("file", fileName) io.Copy(fw1, f) bw.Close() return bw.FormDataContentType(), buf, nil } func submitPdfConversionTask(filePath string, rapidApiKey string) (string, error) { contType, reader, err := createReqBody(filePath, "Sebastian", "Final report", "Reports, Final", "Quarterly Final Report") if err != nil { return "", err } req, err := http.NewRequest("POST", "https://petadata-document-conversion-suite.p.rapidapi.com/SubmitPDFConversionTask", reader) req.Header.Add("Content-Type", contType) req.Header.Add("X-RapidAPI-Key", rapidApiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil || resp.StatusCode != 200 { fmt.Println("Cannot upload file to convert error:", err) return "", err } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { return "", err } return string(b), nil } func getConversionTaskStatus(taskId string, rapidApiKey string) (string, error) { url := fmt.Sprintf("https://petadata-document-conversion-suite.p.rapidapi.com/GetConversionTaskStatus?taskId=%s", taskId) req, err := http.NewRequest("GET", url, nil) req.Header.Add("X-RapidAPI-Key", rapidApiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil || resp.StatusCode != 200 { fmt.Println("Cannot check conversion status of task with error:", err) return "", err } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { return "", err } return string(b), nil } func downloadResult(taskId string, rapidApiKey string) ([]byte, error) { url := fmt.Sprintf("https://petadata-document-conversion-suite.p.rapidapi.com/DownloadResult?taskId=%s", taskId) req, err := http.NewRequest("GET", url, nil) req.Header.Add("X-RapidAPI-Key", rapidApiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil || resp.StatusCode != 200 { fmt.Println("Cannot download converted file with error:", err) return nil, err } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } return b, nil } func main() { filePathToConvert := "<FILE PATH TO CONVERT>" rapidApiKey := "<YOUR RAPIDAPI KEY HERE>" taskId, err := submitPdfConversionTask(filePathToConvert, rapidApiKey) if err != nil { panic(err) } retryCount := 0 for retryCount < 100 { retryCount++ time.Sleep(5 * time.Second) status, err := getConversionTaskStatus(taskId, rapidApiKey) if err != nil { panic(err) } if status == "Completed" { fileBytes, err := downloadResult(taskId, rapidApiKey) if err != nil { panic(err) } err = os.WriteFile("final_report.pdf", fileBytes, 0644) if err != nil { panic(err) } break } else if status == "Waiting" { continue } else if status == "Failed" { panic(errors.New("Cannot convert file")) } else { panic(errors.New("Cannot convert file")) } } }

3 分钟 · 塞巴斯蒂安·克罗西奇

如何使用 Java 将文档转换为 PDF

在本教程中,我们将介绍如何实现文档转换套件的异步方法。您只需将源文档发送到 SubmitTIFFConversionTask 或 SubmitPDFConversionTask API 方法即可接收任务标识符作为响应。还有SubmitDOCXConversionTask方法将PDF文档转换为可编辑的Microsoft Word文档。 收到任务标识符后,您需要通过调用 GetConversionTaskStatus 方法检查任务状态。只要任务状态等于“Waiting”,您需要在几秒钟延迟后调用相同的方法。一旦您从GetConversionTaskStatus方法收到“Completed”,您就可以调用DownloadResult方法来下载最终文档文件。在本教程中,我们使用了 Apache HTTP 客户端库。您可以在 pom.xml 文件中添加下面的依赖项。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <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> 您可以使用下面的 Java 实现。 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 import org.apache.commons.io.FileUtils; 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 DocumentConverter { private static String submitPdfConversionTask(CloseableHttpClient httpClient, String filePathToConvert, String rapidApiKey) throws IOException { File fileToConvert = new File(filePathToConvert); HttpPost submitPDFConversionTaskPost = new HttpPost("https://petadata-document-conversion-suite.p.rapidapi.com/SubmitPDFConversionTask"); submitPDFConversionTaskPost.addHeader("X-RapidAPI-Key", rapidApiKey); byte[] bytes = FileUtils.readFileToByteArray(fileToConvert); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, fileToConvert.getName()); builder.addTextBody("authorName", "Sebastian", ContentType.TEXT_PLAIN); builder.addTextBody("title", "Final report", ContentType.TEXT_PLAIN); builder.addTextBody("keywords", "Reports, Final", ContentType.TEXT_PLAIN); builder.addTextBody("name", "Quarterly Final Report", ContentType.TEXT_PLAIN); HttpEntity requestEntity = builder.build(); submitPDFConversionTaskPost.setEntity(requestEntity); HttpResponse response = httpClient.execute(submitPDFConversionTaskPost); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("Cannot post conversion task"); } HttpEntity responseEntity = response.getEntity(); return EntityUtils.toString(responseEntity, "UTF-8"); } private static String getConversionTaskStatus(CloseableHttpClient httpClient, String taskId, String rapidApiKey) throws IOException { HttpGet getConversionTaskStatus = new HttpGet("https://petadata-document-conversion-suite.p.rapidapi.com/GetConversionTaskStatus?taskId=" + taskId); getConversionTaskStatus.addHeader("X-RapidAPI-Key", rapidApiKey); HttpResponse response = httpClient.execute(getConversionTaskStatus); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("Cannot get conversion 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://petadata-document-conversion-suite.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 converted file"); } HttpEntity responseEntity = response.getEntity(); return EntityUtils.toByteArray(responseEntity); } public static void main(String[] args) throws Exception { String rapidApiKey = "<YOUR RAPIDAPI KEY HERE>"; String filePathToConvert = "<FILE PATH TO CONVERT>"; CloseableHttpClient httpClient = HttpClients.createDefault(); String taskId = submitPdfConversionTask(httpClient, filePathToConvert, rapidApiKey); int retryCount = 0; while (retryCount < 100) { retryCount++; Thread.sleep(5000); String status = getConversionTaskStatus(httpClient, taskId, rapidApiKey); if (status.equals("Completed")) { byte[] fileBytes = downloadResult(httpClient, taskId, rapidApiKey); File outputFile =new File("final_report.pdf"); Files.write(outputFile.toPath(), fileBytes); break; } else if (status.equals("Waiting")) { continue; } else if (status.equals("Failed")) { throw new Exception("Cannot convert file"); } else { throw new Exception("Invalid status"); } } } }

3 分钟 · 塞巴斯蒂安·克罗西奇

如何使用 PHP 将文档转换为 PDF

在本教程中,我们将介绍如何实现图像转换器的异步方法。您只需将源图像发送到 SubmitWebPConversionTask 或任何其他提交 API 方法(如 SubmitBmpConversionTask、SubmitDicomConversionTask 等)即可接收任务标识符作为响应。 收到任务标识符后,您需要通过调用 GetConversionTaskStatus 方法检查任务状态。只要任务状态等于“Waiting”,您需要在几秒钟延迟后调用相同的方法。一旦您从GetConversionTaskStatus方法收到“Completed”,您就可以调用DownloadResult方法来下载最终图像。可以使用下面的 PHP 实现。 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 <?php function submitPdfConversionTask($sourceFilePath, $rapidApiKey) { $curl = curl_init(); $fields = [ 'authorName' => 'John K.', 'title' => 'Curriculum vitae', 'subject' => 'My latest cv', 'keywords' => 'CV, Personal', 'file' => new \CurlFile($sourceFilePath, 'text/plain', basename($sourceFilePath)) ]; curl_setopt_array($curl, [ CURLOPT_URL => "https://petadata-document-conversion-suite.p.rapidapi.com/SubmitPDFConversionTask", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_FAILONERROR => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $fields, CURLOPT_HTTPHEADER => [ "X-RapidAPI-Host: petadata-document-conversion-suite.p.rapidapi.com", "X-RapidAPI-Key: $rapidApiKey" ], ]); $response = curl_exec($curl) or die(curl_error($curl)); $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close ($curl); if($http_status == 200) { return $response; } } function getConversionTaskStatus($taskId, $rapidApiKey) { $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://petadata-document-conversion-suite.p.rapidapi.com/GetConversionTaskStatus?taskId=$taskId", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => [ "X-RapidAPI-Host: petadata-document-conversion-suite.p.rapidapi.com", "X-RapidAPI-Key: $rapidApiKey" ], ]); $response = curl_exec($curl) or die(curl_error($curl)); $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close ($curl); if($http_status == 200) { return $response; } } function downloadResult($fileName, $taskId, $rapidApiKey) { $curl = curl_init(); $fp = fopen($fileName, 'w+'); curl_setopt_array($curl, [ CURLOPT_URL => "https://petadata-document-conversion-suite.p.rapidapi.com/DownloadResult?taskId=$taskId", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_FILE => $fp, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => [ "X-RapidAPI-Host: petadata-document-conversion-suite.p.rapidapi.com", "X-RapidAPI-Key: $rapidApiKey" ], ]); curl_exec($curl) or die(curl_error($curl)); curl_close ($curl); fclose($fp); } $rapidApiKey = "<YOUR RAPIDAPI KEY HERE>"; $filePathToConvert = "<FILE PATH TO CONVERT>"; $taskId = submitPdfConversionTask($filePathToConvert, $rapidApiKey); $retryCount = 0; while ($retryCount < 100){ $retryCount++; sleep(5); $status = getConversionTaskStatus($taskId, $rapidApiKey); if ($status == "Completed") { downloadResult("final_report.pdf", $taskId, $rapidApiKey); break; } else if ($status == "Waiting") { continue; } else if ($status == "Failed") { die("Cannot convert file"); } else { die("Invalid status"); } }

2 分钟 · 塞巴斯蒂安·克罗西奇

如何使用 Visual Basic 将 HTML 转换为 PDF

在本教程中,我们将介绍如何实现 Web 呈现器的异步方法。您只需要将 HTML 内容发送到 SubmitPDFFromHTMLTask 或 SubmitImageFromHTMLTask API 方法即可接收任务标识符作为响应。还有SubmitPDFFromUrlTask和SubmitImageFromUrlTask方法,用于从公共Web Uri呈现PDF或图像。 收到任务标识符后,您需要通过调用 GetRenderingTaskStatus 方法来检查任务状态。只要任务状态等于“Waiting”,您需要在几秒钟延迟后调用相同的方法。一旦你从GetRenderingTaskStatus方法收到“Completed”,你可以调用DownloadResult方法来下载最终文件。您可以使用下面的 Visual Basic 实现。 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 Imports System Imports System.IO Imports System.Net.Http Module Program Async Function SubmitPDFFromHTMLTask(htmlContent As String, uri As String, rapidApiKey As String) As Task(Of String) Using httpClient As New HttpClient() Using form As 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 response = Await httpClient.PostAsync("https://web-renderer.p.rapidapi.com/SubmitPDFFromHTMLTask", form) response.EnsureSuccessStatusCode() Return Await response.Content.ReadAsStringAsync() End Using End Using End Using End Function Async Function GetRenderingTaskStatus(taskId As String, rapidApiKey As String) As Task(Of String) Using httpClient As New HttpClient() httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey) Using response = Await httpClient.GetAsync($"https://web-renderer.p.rapidapi.com/GetRenderingTaskStatus?taskId={taskId}") response.EnsureSuccessStatusCode() Return Await response.Content.ReadAsStringAsync() End Using End Using End Function Async Function DownloadResult(taskId As String, rapidApiKey As String) As Task(Of Byte()) Using httpClient As New HttpClient() httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey) Using response = Await httpClient.GetAsync($"https://web-renderer.p.rapidapi.com/DownloadResult?taskId={taskId}") response.EnsureSuccessStatusCode() Return Await response.Content.ReadAsByteArrayAsync() End Using End Using End Function Public Async Function RenderHtmlAsync() As Task Dim rapidApiKey = "<YOUR RAPIDAPI KEY HERE>" Dim htmlContent = "<HTML CONTENT TO RENDER>" Dim uriOfHtmlContent = "https://www.google.com?hl=en" Dim taskId = Await SubmitPDFFromHTMLTask(htmlContent, uriOfHtmlContent, rapidApiKey) Dim retryCount = 0 Do While (retryCount < 100) retryCount += 1 Await Task.Delay(5000) Dim status = Await GetRenderingTaskStatus(taskId, rapidApiKey) If (status = "Completed") Then Dim fileBytes = Await DownloadResult(taskId, rapidApiKey) Await File.WriteAllBytesAsync("html_from_html.pdf", fileBytes) Exit Do ElseIf (status = "Waiting") Then Continue Do ElseIf (status = "Failed") Then Throw New Exception("Cannot convert file") Else Throw New Exception("Invalid status") End If Loop End Function Sub Main(args As String()) RenderHtmlAsync().Wait() End Sub End Module

2 分钟 · 塞巴斯蒂安·克罗西奇

如何使用 Visual Basic 将文档转换为 PDF

在本教程中,我们将介绍如何实现文档转换套件的异步方法。您只需将源文档发送到 SubmitTIFFConversionTask 或 SubmitPDFConversionTask API 方法即可接收任务标识符作为响应。还有SubmitDOCXConversionTask方法将PDF文档转换为可编辑的Microsoft Word文档。 收到任务标识符后,您需要通过调用 GetConversionTaskStatus 方法检查任务状态。只要任务状态等于“Waiting”,您需要在几秒钟延迟后调用相同的方法。一旦您从GetConversionTaskStatus方法收到“Completed”,您可以调用DownloadResult方法来下载最终文档文件。您可以使用下面的 Visual Basic 实现。 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 Imports System Imports System.IO Imports System.Net.Http Module Program Async Function SubmitPdfConversionTask(filePathToConvert As String, rapidApiKey As String) As Task(Of String) Using httpClient As New HttpClient() Using form As New MultipartFormDataContent() form.Headers.Add("X-RapidAPI-Key", rapidApiKey) form.Add(New StringContent("Sebastian"), "authorName") form.Add(New StringContent("Final report"), "title") form.Add(New StringContent("Reports, Final"), "keywords") form.Add(New StringContent("Quarterly Final Report"), "name") Dim fileBytes = Await File.ReadAllBytesAsync(filePathToConvert) Dim fileName = Path.GetFileName(filePathToConvert) form.Add(New ByteArrayContent(fileBytes, 0, fileBytes.Length), "file", fileName) Using response = Await httpClient.PostAsync("https://petadata-document-conversion-suite.p.rapidapi.com/SubmitPDFConversionTask", form) response.EnsureSuccessStatusCode() Return Await response.Content.ReadAsStringAsync() End Using End Using End Using End Function Async Function GetConversionTaskStatus(taskId As String, rapidApiKey As String) As Task(Of String) Using httpClient As New HttpClient() httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey) Using response = Await httpClient.GetAsync($"https://petadata-document-conversion-suite.p.rapidapi.com/GetConversionTaskStatus?taskId={taskId}") response.EnsureSuccessStatusCode() Return Await response.Content.ReadAsStringAsync() End Using End Using End Function Async Function DownloadResult(taskId As String, rapidApiKey As String) As Task(Of Byte()) Using httpClient As New HttpClient() httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", rapidApiKey) Using response = Await httpClient.GetAsync($"https://petadata-document-conversion-suite.p.rapidapi.com/DownloadResult?taskId={taskId}") response.EnsureSuccessStatusCode() Return Await response.Content.ReadAsByteArrayAsync() End Using End Using End Function Public Async Function ConvertDocumentAsync() As Task Dim rapidApiKey = "<YOUR RAPIDAPI KEY HERE>" Dim filePathToConvert = "<FILE PATH TO CONVERT>" Dim taskId = Await SubmitPdfConversionTask(filePathToConvert, rapidApiKey) Dim retryCount = 0 Do While (retryCount < 100) retryCount += 1 Await Task.Delay(5000) Dim status = Await GetConversionTaskStatus(taskId, rapidApiKey) If (status = "Completed") Then Dim fileBytes = Await DownloadResult(taskId, rapidApiKey) Await File.WriteAllBytesAsync("final_report.pdf", fileBytes) Exit Do ElseIf (status = "Waiting") Then Continue Do ElseIf (status = "Failed") Then Throw New Exception("Cannot convert file") Else Throw New Exception("Invalid status") End If Loop End Function Sub Main(args As String()) ConvertDocumentAsync().Wait() End Sub End Module

2 分钟 · 塞巴斯蒂安·克罗西奇

如何使用Java将HTML转换为PDF

在本教程中,我们将介绍如何实现 Web 呈现器的异步方法。您只需要将 HTML 内容发送到 SubmitPDFFromHTMLTask 或 SubmitImageFromHTMLTask API 方法即可接收任务标识符作为响应。还有SubmitPDFFromUrlTask和SubmitImageFromUrlTask方法,用于从公共Web Uri呈现PDF或图像。 收到任务标识符后,您需要通过调用 GetRenderingTaskStatus 方法来检查任务状态。只要任务状态等于“Waiting”,您需要在几秒钟延迟后调用相同的方法。一旦您从GetRenderingTaskStatus方法收到“Completed”,您就可以调用DownloadResult方法来下载最终文件。在本教程中,我们使用了 Apache HTTP 客户端库。您可以在 pom.xml 文件中添加下面的依赖项。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <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> 您可以使用下面的 Java 实现。 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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"); } } } }

3 分钟 · 塞巴斯蒂安·克罗西奇