How to convert HMTL to PDF in PHP

It is quite easy to utilize HTML to PDF API in your PHP scripts.

Prerequisites

Obtain your access token

Please visit tokens page and copy your access token. We will refer to the token as TOKEN in this guide.

Usage

Convert a URL to PDF and save to disk

This snippet uses HTML to PDF API to generate a PDF and stream back the resulting file. After receiving the response, we write the file to out.pdf in this sample but it’s up to you to use it as you wish.

$TOKEN = "TOKEN";
$URL = "http://google.com";

$result = file_get_contents("https://restpack.io/api/html2pdf/v4/convert?access_token=" . urlencode($TOKEN) . "&url=" . urlencode($URL));
file_put_contents("out.php", $result);

Convert an HTML string to PDF

Here, instead of sending a url querystring parameter, we are POSTing a html_data paramter. It can contain complex html, css, inline JS etc.

$TOKEN = "TOKEN";
$HTML = "<strong>Bold text here</strong> and regular here..";

// These are the request paramteres. You can check the full list of possible parameters at
// https://restpack.io/html2pdf/docs#route
$postdata = http_build_query(
  array(
    'access_token' => $TOKEN,
    'delay' => "1" //wait 1 second before convert
  )
);

// Build a POST request
$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $postdata
  )
);

$context = stream_context_create($opts);

$result = file_get_contents("https://restpack.io/api/html2pdf/v4/convert", false, $context);
file_put_contents("out.php", $result);

Obtain a reusable URL for converted PDF

If you don’t need to store / process the output PDF, you can use our publicly accessible CDN servers to serve the PDF file.

$TOKEN = "TOKEN";
$URL = "http://google.com";

$result = file_get_contents("https://restpack.io/api/html2pdf/v4/convert?json=true&access_token=" . urlencode($TOKEN) . "&url=" . urlencode($URL));

// Response is a JSON document, let's decode it.
$info = json_decode($result);

// Redirect the user to the PDF document
header('Location: ' . $info['mediaLink']);

For detailed usage instructions, please check the Documentation page.