PHP Integration

Learn how to generate PDFs from your PHP application using the built-in cURL extension or Guzzle HTTP client.

Why use PixelToPdf with PHP?

PHP powers millions of web applications, and PixelToPdf integrates seamlessly with any PHP project. Whether you're using vanilla PHP, Laravel, Symfony, or any other framework, our API makes PDF generation straightforward. Perfect for generating invoices, receipts, reports, and any document your users need.

Prerequisites

  • PHP 7.4+ (8.x recommended for best performance)
  • cURL extension enabled (usually enabled by default in most PHP installations)
  • A PixelToPdf API key from your dashboard (free tier available)

Basic Example with cURL

This example uses PHP's built-in cURL extension to convert a webpage to PDF. We use getenv() to securely read the API key from environment variables.

convert-url.php
<?php

$ch = curl_init('https://api.pixeltopdf.com/convert/pdf');

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: ' . getenv('PIXELTOPDF_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'source' => 'https://example.com',
    ]),
]);

$pdf = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($statusCode !== 200) {
    die('PDF generation failed');
}

file_put_contents('output.pdf', $pdf);
echo "PDF saved to output.pdf\n";

How it works: The curl_setopt_array() function configures all cURL options in one call. CURLOPT_RETURNTRANSFER tells cURL to return the response as a string instead of outputting it directly. The PDF binary data is then saved using file_put_contents().

Convert HTML String

For dynamic documents, pass your HTML directly as a string. PHP's heredoc syntax (<<<HTML) makes it easy to write multi-line HTML without escaping quotes.

convert-html.php
<?php

$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; padding: 40px; }
    h1 { color: #333; }
  </style>
</head>
<body>
  <h1>Hello, PixelToPdf!</h1>
  <p>This PDF was generated from HTML.</p>
</body>
</html>
HTML;

$ch = curl_init('https://api.pixeltopdf.com/convert/pdf');

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: ' . getenv('PIXELTOPDF_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'source' => $html,
        'format' => 'A4',
        'margin' => ['top' => '20mm', 'bottom' => '20mm', 'left' => '20mm', 'right' => '20mm'],
    ]),
]);

$pdf = curl_exec($ch);
curl_close($ch);

file_put_contents('output.pdf', $pdf);

Tip: You can use PHP template engines like Blade, Twig, or simple include() statements to generate your HTML dynamically. The margin option accepts values in mm, cm, in, or px.

With Guzzle

Guzzle is PHP's most popular HTTP client, offering a cleaner API than raw cURL. Install it with Composer: composer require guzzlehttp/guzzle

convert-guzzle.php
<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('https://api.pixeltopdf.com/convert/pdf', [
    'headers' => [
        'X-API-Key' => getenv('PIXELTOPDF_API_KEY'),
        'Content-Type' => 'application/json',
    ],
    'json' => [
        'source' => 'https://example.com',
        'format' => 'A4',
    ],
]);

file_put_contents('output.pdf', $response->getBody());

How it works: Guzzle's json option automatically encodes your array to JSON and sets the Content-Type header. The getBody() method returns the response body as a stream that can be written directly to a file.

With Laravel

Laravel's HTTP facade provides an elegant way to make HTTP requests. This controller renders a Blade template and converts it to PDF for download. Store your API key in config/services.php for proper configuration management.

InvoiceController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class InvoiceController extends Controller
{
    public function download(string $invoiceId)
    {
        $html = view('invoices.template', ['invoiceId' => $invoiceId])->render();

        $response = Http::withHeaders([
            'X-API-Key' => config('services.pixeltopdf.key'),
        ])->post('https://api.pixeltopdf.com/convert/pdf', [
            'source' => $html,
            'format' => 'A4',
        ]);

        if (!$response->successful()) {
            abort(500, 'PDF generation failed');
        }

        return response($response->body())
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', "attachment; filename=invoice-{$invoiceId}.pdf");
    }
}

Best practice: Use view()->render() to convert Blade templates to HTML strings. Store your API key in config/services.php as 'pixeltopdf' => ['key' => env('PIXELTOPDF_API_KEY')] and access it via config('services.pixeltopdf.key').

Error Handling

This reusable function wraps the API call with proper error handling. Custom exceptions make it easy to catch and handle specific error cases in your application logic.

<?php

class PixelToPdfException extends Exception {}

function generatePdf(string $source): string
{
    $ch = curl_init('https://api.pixeltopdf.com/convert/pdf');

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'X-API-Key: ' . getenv('PIXELTOPDF_API_KEY'),
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode(['source' => $source]),
    ]);

    $response = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    switch ($statusCode) {
        case 200:
            return $response;
        case 401:
            throw new PixelToPdfException('Invalid API key');
        case 402:
            throw new PixelToPdfException('No credits remaining');
        case 429:
            throw new PixelToPdfException('Rate limit exceeded');
        default:
            throw new PixelToPdfException('PDF generation failed: ' . $response);
    }
}

Important: The API returns different status codes for different error types: 401 for authentication issues, 402 when you need more credits, and 429 when you've hit the rate limit. Handle each appropriately in production.

Next steps

You've mastered the basics! Learn about headers, footers, page breaks, and advanced styling in our API documentation.