Convert HTML to PDF in PHP
Convert HTML to PDF in PHP using the HTML2PDFAPI REST API. Works with Laravel, Symfony, and vanilla PHP.
Quick Start with cURL
<?php
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://html2pdfapi.com/render',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_KEY',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode([
'html' => '<h1>Hello World</h1>',
'format' => 'pdf'
])
]);
$response = curl_exec($ch);
curl_close($ch);
file_put_contents('output.pdf', $response);Using Guzzle
<?php
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('https://html2pdfapi.com/render', [
'headers' => [
'Authorization' => 'Bearer ' . env('HTML2PDFAPI_KEY'),
'Content-Type' => 'application/json'
],
'json' => [
'html' => '<h1>Hello World</h1>',
'format' => 'pdf',
'options' => [
'format' => 'A4',
'printBackground' => true
]
]
]);
$pdfContent = $response->getBody()->getContents();Laravel Integration
<?php
// app/Http/Controllers/PdfController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class PdfController extends Controller
{
public function generate(Request $request)
{
$html = view('invoices.template', [
'invoice' => $request->invoice
])->render();
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . config('services.html2pdfapi.key')
])->post('https://html2pdfapi.com/render', [
'html' => $html,
'format' => 'pdf'
]);
return response($response->body())
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', 'attachment; filename="invoice.pdf"');
}
}Available Options
| Option | Type | Description |
|---|---|---|
| format | string | Output format: 'pdf', 'png', 'jpeg', 'webp' |
| html | string | HTML content to convert |
| url | string | URL to convert |
| options.format | string | Page size: 'A4', 'Letter', etc. |
| options.landscape | boolean | Landscape orientation |
| options.printBackground | boolean | Include background colors/images |
Other Integrations
See Use Cases
PDF generation for Laravel, Symfony, and vanilla PHP
Use cURL, Guzzle, or Laravel's HTTP client.