How to Convert a URL to PDF in PHP

Cloudmersive
2 min readMar 26, 2024

--

With just a few lines of complementary PHP code, we can easily turn webpage URL contents into PDFs.

In the brief demonstration below, we’ll call a free “URL to PDF” conversion API using PHP code. This will render our webpage URL and create a PDF document with its contents.

Our first step is to install the client SDK. To install using Composer, let’s run the below command from the command line:

composer require cloudmersive/cloudmersive_document_convert_api_client

Next, let’s copy the below code to call the function.

<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');



$apiInstance = new Swagger\Client\Api\ConvertWebApi(


new GuzzleHttp\Client(),
$config
);
$input = new \Swagger\Client\Model\UrlToPdfRequest(); // \Swagger\Client\Model\UrlToPdfRequest | URL to PDF request parameters

try {
$result = $apiInstance->convertWebUrlToPdf($input);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertWebApi->convertWebUrlToPdf: ', $e->getMessage(), PHP_EOL;
}
?>

Now let’s take care of a few important details.

We’ll need a free Cloudmersive API key to authorize our requests — this will allow us to convert up to 800 webpage URLs per month with no commitments. We can copy that into the $config snippet.

To structure our input request with our URL, we can follow the JSON example below:

{
"Url": "string",
"ExtraLoadingWait": 0,
"IncludeBackgroundGraphics": true,
"ScaleFactor": 0
}

Specifying extra loading wait time will help with websites that take a little longer to fully render.

That’s all there is to it — no more code required! Now we can easily save PDFs of individual webpage URLs.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.