PHP

Integrate DoCreate with PHP

This guide shows how to generate PDFs with DoCreate using PHP and the built-in cURL extension.

Prerequisites

Ensure the cURL extension is enabled in your PHP installation. It is included by default in most PHP environments. You can verify it by running:

php -m | grep curl

Basic Example

Generate a PDF and save it to a file:

<?php

$apiUrl = 'https://api.docreate.io/api/pdf/external';
$apiKey = getenv('DOCREATE_API_KEY');

$payload = json_encode([
    'html' => '<h1>Hello from DoCreate</h1><p>Generated with PHP.</p>',
    'css'  => 'h1 { color: #2563eb; } p { color: #555; }',
]);

$ch = curl_init($apiUrl);

curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_TIMEOUT        => 30,
]);

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

if (curl_errno($ch)) {
    die('cURL error: ' . curl_error($ch));
}

curl_close($ch);

if ($httpCode !== 200) {
    $error = json_decode($response, true);
    die('PDF generation failed: ' . ($error['error'] ?? "HTTP $httpCode"));
}

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

Reusable Function

A production-ready function with full error handling:

<?php

/**
 * Generate a PDF using the DoCreate API.
 *
 * @param string $apiKey Your DoCreate API key.
 * @param string $html   The HTML content for the PDF.
 * @param string $css    Optional CSS styles.
 *
 * @return string The raw PDF bytes.
 *
 * @throws RuntimeException If the API returns an error.
 */
function generatePdf(string $apiKey, string $html, string $css = ''): string
{
    $ch = curl_init('https://api.docreate.io/api/pdf/external');

    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS     => json_encode([
            'html' => $html,
            'css'  => $css,
        ]),
        CURLOPT_TIMEOUT        => 30,
    ]);

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

    curl_close($ch);

    if ($curlError) {
        throw new RuntimeException("cURL error: $curlError");
    }

    if ($httpCode !== 200) {
        $body = json_decode($response, true);
        $message = $body['error'] ?? "HTTP $httpCode";
        throw new RuntimeException("PDF generation failed: $message");
    }

    return $response;
}

// Usage
$apiKey = getenv('DOCREATE_API_KEY');

try {
    $pdf = generatePdf($apiKey, '<h1>Invoice</h1><p>Amount: $2,800.00</p>', 'h1 { color: #1a1a1a; }');
    file_put_contents('invoice.pdf', $pdf);
    echo "PDF generated successfully\n";
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}

Laravel Integration

Serve a generated PDF as a download from a Laravel controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use RuntimeException;

class InvoiceController extends Controller
{
    public function downloadPdf(string $invoiceId): Response
    {
        $invoice = Invoice::findOrFail($invoiceId);

        $html = view('invoices.pdf', ['invoice' => $invoice])->render();
        $css = file_get_contents(resource_path('css/invoice.css'));

        $pdf = $this->generatePdf($html, $css);

        return response($pdf, 200, [
            'Content-Type'        => 'application/pdf',
            'Content-Disposition' => "attachment; filename=\"invoice-{$invoice->number}.pdf\"",
        ]);
    }

    private function generatePdf(string $html, string $css = ''): string
    {
        $ch = curl_init('https://api.docreate.io/api/pdf/external');

        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . config('services.docreate.api_key'),
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS     => json_encode([
                'html' => $html,
                'css'  => $css,
            ]),
            CURLOPT_TIMEOUT        => 30,
        ]);

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

        curl_close($ch);

        if ($httpCode !== 200) {
            $body = json_decode($response, true);
            throw new RuntimeException('DoCreate API error: ' . ($body['error'] ?? "HTTP $httpCode"));
        }

        return $response;
    }
}

Add the API key to your Laravel configuration:

// config/services.php
'docreate' => [
    'api_key' => env('DOCREATE_API_KEY'),
],
# .env
DOCREATE_API_KEY=your_api_key_here

Environment Variables

Always store your API key as an environment variable. In PHP, you can access it with getenv() or $_ENV:

$apiKey = getenv('DOCREATE_API_KEY');

For Apache or Nginx, set the variable in your server configuration or .env file rather than hard-coding it in your PHP files.