In this guide you will learn how to convert HTML to PDF in PHP by calling the HTML2PDF REST API with your own PHP code.

We will cover:

  • Converting a URL to PDF with PHP
  • Converting raw HTML to PDF
  • Setting page size, orientation and layout options
  • Handling errors and status codes

The HTML2PDF API accepts both URLs and HTML and returns a ready-to-download PDF document. You send a simple HTTP GET or POST request to https://api.html2pdf.co.uk/ with your license key and parameters.

Note that we also have a PHP library available that takes care of the heavy lifting for you.


Prerequisites

  • PHP 7 or higher
  • The curl extension enabled (recommended)
  • An HTML2PDF license key

1. Convert a URL to PDF in PHP

The most basic request you can send looks like this:

https://api.html2pdf.co.uk/?license=yourlicensekey&url=https://example.com

Below is a simple example using file_get_contents. This is useful for quick scripts and cron jobs.

<?php

$license = 'yourlicensekey'; // replace with your real license key
$url     = 'https://example.com';

$query = http_build_query([
    'license' => $license,
    'url'     => $url,
]);

$apiUrl = "https://api.html2pdf.co.uk/?{$query}";

// Get the PDF binary from the API
$pdf = file_get_contents($apiUrl);

if ($pdf === false) {
    die('Error calling HTML2PDF API');
}

// Save PDF to disk
file_put_contents(__DIR__ . '/example.pdf', $pdf);

echo "PDF created successfully.\n";

For more control and better error handling you can use cURL instead:

<?php

$license = 'yourlicensekey';
$url     = 'https://example.com';

$params = [
    'license' => $license,
    'url'     => $url,
];

$ch = curl_init('https://api.html2pdf.co.uk/?' . http_build_query($params));

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT        => 60,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($response === false) {
    throw new RuntimeException('cURL error: ' . curl_error($ch));
}

curl_close($ch);

if ($httpCode !== 200) {
    throw new RuntimeException('HTML2PDF API error. HTTP status: ' . $httpCode);
}

file_put_contents(__DIR__ . '/example.pdf', $response);
echo "PDF created.\n";

2. Convert raw HTML to PDF in PHP

If you do not have a public URL or you generate HTML dynamically, you can send raw HTML to the API instead by passing the html parameter. For larger content you should use a POST request.

<?php

$license = 'yourlicensekey';

$html = '<html><body><h1>Hello from PHP</h1><p>Converted with HTML2PDF.</p></body></html>';

$postFields = [
    'license' => $license,
    'html'    => $html,
];

$ch = curl_init('https://api.html2pdf.co.uk/');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $postFields,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($response === false) {
    throw new RuntimeException('cURL error: ' . curl_error($ch));
}

curl_close($ch);

if ($httpCode !== 200) {
    throw new RuntimeException('HTML2PDF API error. HTTP status: ' . $httpCode);
}

file_put_contents(__DIR__ . '/html-example.pdf', $response);

Make sure the HTML you pass is valid (for example with <html> and <body> tags) so the rendering engine can lay out the page correctly.


3. Setting conversion options

You can control the output by passing additional parameters to the API. Some of the most common options are:

  • page_size (for example A4 or Letter)
  • orientation (portrait or landscape)
  • top, bottom, left, right (margins)
  • css_media_type (screen or print)
  • lazy_load and wait_time for pages that rely on JavaScript

Here is an example with several options set:

<?php

$license = 'yourlicensekey';
$url     = 'https://example.com/report';

$params = [
    'license'        => $license,
    'url'            => $url,
    'page_size'      => 'A4',
    'orientation'    => 'portrait',
    'css_media_type' => 'print',
    'lazy_load'      => 'true',
    'wait_time'      => '2000',
    'title'          => 'Example Report',
    'filename'       => 'example-report.pdf',
];

$ch = curl_init('https://api.html2pdf.co.uk/?' . http_build_query($params));

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($response === false) {
    throw new RuntimeException('cURL error: ' . curl_error($ch));
}

curl_close($ch);

if ($httpCode !== 200) {
    throw new RuntimeException('HTML2PDF API error. HTTP status: ' . $httpCode);
}

file_put_contents(__DIR__ . '/report.pdf', $response);

For a complete list of parameters, see the setting options section of the API documentation.

Tip: Set your default layout options (page size, margins, header/footer, etc.) once in the members area. You can then keep your PHP code very simple and override options only when needed.

4. Handling Errors

When something goes wrong the API returns an HTTP error code instead of a PDF. Some of the most important codes are:

CodeDescription
200 OKConversion succeeded and the response body contains the PDF
400 Bad RequestNo URL or HTML was provided
401 Authorization requiredMissing or invalid license key
429 Too Many RequestsYou exceeded the limits of your plan
504 / 599Timeout or connectivity problems when fetching the URL

In PHP you can check the status code returned by cURL and act accordingly. For example, you can log the problem, show a friendly error to the user or retry the request if it was a timeout.


5. Next Steps

You now know how to convert HTML to PDF in PHP with the HTML2PDF API. Next you may want to: