How to convert web page to PDF from link asynchronously for HTML to PDF API in PHP with PDF.co Web API

How to convert web page to PDF from link asynchronously for HTML to PDF API in PHP: How To Tutorial

Today you are going to learn how to convert a web page to PDF from links asynchronously in PHP. HTML to PDF API in PHP can be implemented with PDF.co Web API. PDF.co Web API is the Rest API that provides a set of data extraction functions, tools for document manipulation, splitting, and merging of pdf files. Includes built-in OCR, image recognition, can generate and read barcodes from images, scans, and pdf.

This rich sample source code in PHP for PDF.co Web API includes the number of functions and options you should do calling the API to implement HTML to PDF API. For the implementation of this functionality, please copy and paste the code below into your app using the code editor. Then compile and run your app. The use of PDF.co Web API in PHP is also explained in the documentation included along with the product.

The trial version of ByteScout is available for free download from our website. This and other source code samples for PHP and other programming languages are available.

On-demand (REST Web API) version:
 Web API (on-demand version)

On-premise offline SDK for Windows:
 60 Day Free Trial (on-premise)

Source code for this sample is also available at our GitHub repository at this link. GitHub repository also contains various implementations in other programming languages too, please explore!

We will be reviewing the source code and its output. Later we’ll analyze the code.

web-page-to-pdf-async.php

      
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Cloud API asynchronous "Web Page to PDF" job example (allows to avoid timeout errors).</title> </head> <body> <?php // Cloud API asynchronous "Web Page to PDF" job example. // Allows avoiding timeout errors when processing huge or scanned PDF documents. // The authentication key (API Key). // Get your own by registering at https://app.pdf.co/documentation/api $apiKey = "***********************************"; // URL of web page to convert to PDF document. $sourceUrl = "http://www.usa.gov"; // Prepare URL for `Web Page to PDF` API call $url = "https://api.pdf.co/v1/pdf/convert/from/url"; // Prepare requests params $parameters = array(); $parameters["name"] = "result.pdf"; $parameters["url"] = $sourceUrl; $parameters["async"] = true; // (!) Make asynchronous job // Create Json payload $data = json_encode($parameters); // Create request $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json")); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Execute request $result = curl_exec($curl); if (curl_errno($curl) == 0) { $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($status_code == 200) { $json = json_decode($result, true); if ($json["error"] == false) { // URL of generated PDF file that will available after the job completion $resultFileUrl = $json["url"]; // Asynchronous job ID $jobId = $json["jobId"]; // Check the job status in a loop do { $status = CheckJobStatus($jobId, $apiKey); // Possible statuses: "working", "failed", "aborted", "success". // Display timestamp and status (for demo purposes) echo "<p>" . date(DATE_RFC2822) . ": " . $status . "</p>"; if ($status == "success") { // Display link to the file with conversion results echo "<div><h2>Conversion Result:</h2><a href='" . $resultFileUrl . "' target='_blank'>" . $resultFileUrl . "</a></div>"; break; } else if ($status == "working") { // Pause for a few seconds sleep(3); } else { echo $status . "<br/>"; break; } } while (true); } else { // Display service reported error echo "<p>Error: " . $json["message"] . "</p>"; } } else { // Display request error echo "<p>Status code: " . $status_code . "</p>"; echo "<p>" . $result . "</p>"; } } else { // Display CURL error echo "Error: " . curl_error($curl); } // Cleanup curl_close($curl); function CheckJobStatus($jobId, $apiKey) { $status = null; // Create URL $url = "https://api.pdf.co/v1/job/check"; // Prepare requests params $parameters = array(); $parameters["jobid"] = $jobId; // Create Json payload $data = json_encode($parameters); // Create request $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json")); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Execute request $result = curl_exec($curl); if (curl_errno($curl) == 0) { $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($status_code == 200) { $json = json_decode($result, true); if ($json["error"] == false) { $status = $json["status"]; } else { // Display service reported error echo "<p>Error: " . $json["message"] . "</p>"; } } else { // Display request error echo "<p>Status code: " . $status_code . "</p>"; echo "<p>" . $result . "</p>"; } } else { // Display CURL error echo "Error: " . curl_error($curl); } // Cleanup curl_close($curl); return $status; } ?> </body> </html>

Output

This is a simple and straight-forward code snippet. Let’s break it up and try to understand it.

We are aiming for converting a URL to PDF. Initially, we’re preparing the necessary data for PDF.co’s request.

$apiKey Holds PDF.co API Key value. This key is necessary for PDF.co endpoint execution.
$SourceUrl Input website URL for PDF convert.

PDF.co endpoint https://api.pdf.co/v1/pdf/convert/from/url is used to convert URL to PDF. Input data is in JSON payload format. An array is prepared and then converted to JSON.

// Prepare requests params
$parameters = array();
$parameters["name"] = "result.pdf";
$parameters["url"] = $sourceUrl;
$parameters["async"] = true;  // (!) Make asynchronous job

// Create Json payload
$data = json_encode($parameters);

As you have noticed, we’re adding an additional parameter async. Whenever this parameter is provided PDF.co request is executed in asynchronous mode and JOB is returned in the output.

Using curl_init, we’re preparing POST request. Please not we’re passing PDF.co API key in header with x-api-key parameter. Response data are stored in $result variable.

// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

// Execute request
$result = curl_exec($curl);

As we’re executing this request in async mode, it’s returning Job ID along with output URL in the response. Until this job is completed, the output URL will not point to the final PDF. We’re calling method CheckJobStatus to track whether job is completed or not. This function CheckJobStatus is calling PDF.co endpoint https://api.pdf.co/v1/job/check to retrieve status. When job status is success, we mark the job as completed and write Output PDF URL in response HTML.

                $status = CheckJobStatus($jobId, $apiKey); // Possible statuses: "working", "failed", "aborted", "success".
                
                // Display timestamp and status (for demo purposes)
                echo "<p>" . date(DATE_RFC2822) . ": " . $status . "</p>";
                
                if ($status == "success")
                {
                    // Display link to the file with conversion results
                    echo "<div><h2>Conversion Result:</h2><a href='" . $resultFileUrl . "' target='_blank'>" . $resultFileUrl . "</a></div>";
                    break;
                }

As shown in the output image, the result contains a PDF representation of the website. This sample demonstrates a very simple use-case. We can provide an additional PDF.co endpoint parameters to generate output as per our requirements. Please refer to PDF.co documentations for more information.

Thank you for reading!

VIDEO

ON-PREMISE OFFLINE SDK

Get 60 Day Free Trial

See also:

ON-DEMAND REST WEB API

Get Your API Key

See also:

Related Samples: