How to generate a PDF from HTML in PHP and Laravel
Published 2 min read
In PHP, turning HTML into a PDF usually means installing a library or a binary on the server and keeping it working. With an API it is one HTTP request, which PHP already knows how to make. This guide shows it in plain PHP and in Laravel with the rustedf.cloud API.
Plain PHP with cURL
<?php
$payload = [ 'html' => '<h1>Invoice {{ number }}</h1><p>{{ customer }}</p>', 'data' => ['number' => '2025-0042', 'customer' => 'Ana Souza'],];
$ch = curl_init('https://api.rustedf.com/v1/render');curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('RUSTEDF_KEY'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode($payload), CURLOPT_TIMEOUT => 40,]);
$body = curl_exec($ch);$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);curl_close($ch);
if ($status !== 200) { $error = json_decode($body, true)['error'] ?? []; throw new RuntimeException($error['message'] ?? "Render failed ($status)");}
file_put_contents('invoice.pdf', $body);The body of a successful response is the PDF. On a failure it is JSON, with a stable code
for your logic and a message for people. Set the timeout above the time limit of your plan,
so your own request does not give up before the service does.
Laravel
Keep the key in .env and read it through the config, never from a view or from the
browser.
RUSTEDF_KEY=rfk_...
// config/services.php'rustedf' => [ 'key' => env('RUSTEDF_KEY'), 'url' => 'https://api.rustedf.com',],use Illuminate\Support\Facades\Http;
public function invoice(Invoice $invoice){ $response = Http::withToken(config('services.rustedf.key')) ->timeout(40) ->post(config('services.rustedf.url') . '/v1/render', [ 'template_id' => config('invoices.template_id'), 'locale' => 'pt-BR', 'data' => [ 'number' => $invoice->number, 'customer' => ['name' => $invoice->customer->name], 'total' => (string) $invoice->total, ], ]);
if ($response->failed()) { report(new \RuntimeException($response->json('error.message') ?? 'Render failed')); abort(502, 'The invoice could not be generated.'); }
return response($response->body(), 200, [ 'Content-Type' => 'application/pdf', 'Content-Disposition' => 'inline; filename="invoice-' . $invoice->number . '.pdf"', ]);}To keep the file instead of streaming it, use Storage::put("invoices/{$invoice->number}.pdf", $response->body()).
Saved template or inline HTML
The example above calls a saved template by id, which you edit in the portal with a live preview. That is the better choice when the same layout is generated often.
To send the HTML yourself, put it in html instead of template_id. Two cautions:
- The HTML is itself a template, so
{{ }}and{% %}in it are read by the service. Pass anything a user typed throughdata, which is escaped, rather than pasting it into the string. - If you render HTML with Blade first, remember that the result is then treated as a template
again. A name that contains
{{would be interpreted, not printed.
Errors worth handling
| Status | code |
What to do |
|---|---|---|
| 401 | unauthorized |
The key is missing, wrong or revoked. |
| 402 | insufficient_credits |
No credits left. Nothing was rendered. |
| 422 | invalid_template |
The template or its data failed. Read message. |
| 429 | rate_limited |
Wait for the Retry-After header and retry. |
| 503 | busy |
The service is busy. Wait for Retry-After and retry. |
| 504 | render_timeout |
The document took longer than your plan allows. |
A credit is taken when a render starts and returned if it fails, so a failed call costs nothing.
Read Rendering a PDF, Authentication and Errors and limits.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
Convert a web page to PDF in C# without a headless browser
Fetch a page with HttpClient and turn its HTML into a PDF with one API call in C#. Which pages this suits, which it does not, and how to check before you rely on it.
3 min read
Code and integrations
C# PDF report generator: a paged table with totals and page numbers
Build a PDF report in C# from a list of objects: a table whose header repeats on every page, a total, page numbers and the page count, with one HTTP call.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read