· 9 min read
Generate PDF Invoices in PHP (Yii2 / Laravel) via REST API
Offload PDF rendering to QuartzAPI: your Yii2 or Laravel app only sends invoice JSON over REST and streams the finished PDF to the browser.
Generating PDF invoices in PHP with traditional libraries like mPDF or Dompdf often leads to heavy server memory consumption, broken CSS layouts, and maintenance headaches.
By offloading the rendering engine to QuartzAPI, your PHP application only needs a fast, lightweight HTTP POST with a JSON payload containing the invoice data. Layout lives in the Visual Builder; your Yii2 or Laravel code stays focused on business data.
Prerequisites
- PHP 7.4+ or 8.x
- A QuartzAPI account and API key
-
An active template code created in the QuartzAPI Visual Builder
(e.g.
INVOICE_V1) -
Optional: Laravel HTTP client, or Yii2
yiisoft/yii2-httpclient
Step 1: prepare your JSON payload data
Whether you fetch invoice data from Eloquent (Laravel) or Active Record (Yii2), structure it as a clean
associative array that matches your template placeholders. QuartzAPI expects document data under
data, typically with a master object and line items in master.items.
<?php
$invoiceData = [
'templateCode' => 'INVOICE_V1',
'outputFormat' => 'pdf',
'externalId' => 'INV-2026-0042',
'data' => [
'master' => [
'invoice_number' => 'INV-2026-0042',
'date' => date('Y-m-d'),
'customer_name' => 'Acme Corporation',
'customer_vat' => 'US123456789',
'customer_email' => 'billing@acme.com',
'subtotal' => 1090.00,
'tax' => 239.80,
'grand_total' => 1329.80,
'items' => [
[
'description' => 'Web Development Services',
'quantity' => 10,
'price' => 85.00,
'total' => 850.00,
],
[
'description' => 'Cloud Hosting (Annual)',
'quantity' => 1,
'price' => 240.00,
'total' => 240.00,
],
],
],
],
];
Field names must match the bindings in your template. For a deeper walkthrough of the JSON-to-PDF pattern, see How to generate PDF invoices from JSON.
Step 2: implementation in Laravel
Use Laravel’s HTTP client (Illuminate\Support\Facades\Http) to call
generate-document, then download the PDF binary and return it to the browser.
Store the API key in config/services.php (e.g. services.quartzapi.key).
Controller example (InvoiceController.php):
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
class InvoiceController extends Controller
{
public function downloadPdf(int $invoiceId)
{
// 1. Build payload from your Eloquent model (simplified here)
$payload = [
'templateCode' => 'INVOICE_V1',
'outputFormat' => 'pdf',
'externalId' => 'INV-2026-0042',
'data' => [
'master' => [
'invoice_number' => 'INV-2026-0042',
'grand_total' => 1329.80,
// … remaining attributes / items …
'items' => [],
],
],
];
// 2. Generate document
$generate = Http::withHeaders([
'Authorization' => 'Bearer ' . config('services.quartzapi.key'),
'Content-Type' => 'application/json',
])->post('https://backend.quartzapi.com/index.php?r=api/v1-jobs/generate-document', $payload);
if ($generate->failed()) {
return back()->with('error', 'Failed to generate PDF invoice.');
}
$documentId = $generate->json('result.documentId');
$downloadUrl = $generate->json('result.downloadUrl')
?: 'https://backend.quartzapi.com/index.php?r=api/v1-documents/download&uid=' . urlencode((string) $documentId);
// 3. Fetch PDF bytes
$pdf = Http::withHeaders([
'Authorization' => 'Bearer ' . config('services.quartzapi.key'),
])->get($downloadUrl);
if ($pdf->failed()) {
return back()->with('error', 'Failed to download PDF invoice.');
}
// 4. Browser download
return response($pdf->body(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Invoice-2026-0042.pdf"',
]);
}
}
Step 3: implementation in Yii2
In Yii2 you can use yii\httpclient\Client (or cURL) inside a controller action.
Keep the API key in params (e.g. Yii::$app->params['quartzApiKey']).
Controller example (InvoiceController.php):
<?php
namespace app\controllers;
use Yii;
use yii\httpclient\Client;
use yii\web\Controller;
use yii\web\ServerErrorHttpException;
class InvoiceController extends Controller
{
public function actionDownloadPdf($id)
{
$payload = [
'templateCode' => 'INVOICE_V1',
'outputFormat' => 'pdf',
'externalId' => 'INV-2026-0042',
'data' => [
'master' => [
'invoice_number' => 'INV-2026-0042',
'grand_total' => 1329.80,
'items' => [],
],
],
];
$client = new Client();
$generate = $client->createRequest()
->setMethod('POST')
->setUrl('https://backend.quartzapi.com/index.php?r=api/v1-jobs/generate-document')
->addHeaders([
'Authorization' => 'Bearer ' . Yii::$app->params['quartzApiKey'],
'Content-Type' => 'application/json',
])
->setContent(json_encode($payload))
->send();
if (!$generate->isOk) {
throw new ServerErrorHttpException('PDF rendering service unavailable.');
}
$body = $generate->data;
$documentId = $body['result']['documentId'] ?? '';
$downloadUrl = $body['result']['downloadUrl']
?? ('https://backend.quartzapi.com/index.php?r=api/v1-documents/download&uid=' . rawurlencode($documentId));
$pdf = $client->createRequest()
->setMethod('GET')
->setUrl($downloadUrl)
->addHeaders([
'Authorization' => 'Bearer ' . Yii::$app->params['quartzApiKey'],
])
->send();
if (!$pdf->isOk) {
throw new ServerErrorHttpException('PDF download failed.');
}
return Yii::$app->response->sendContentAsFile(
$pdf->content,
'Invoice-2026-0042.pdf',
['mimeType' => 'application/pdf', 'inline' => true]
);
}
}
Key benefits over mPDF / Dompdf
- Zero RAM overhead on your app servers: memory stays predictable regardless of document size — rendering runs on QuartzAPI.
- No CSS workarounds: layout is maintained in the visual drag-and-drop editor, not in PHP HTML strings.
- Instant design updates: change headers, fonts, or columns without pushing code or running deployments.
| Approach | Layout ownership | App server load |
|---|---|---|
| mPDF / Dompdf in-app | PHP / HTML in your repo | High (CPU + RAM per PDF) |
| QuartzAPI REST | Cloud Visual Builder | One HTTP call + stream |
Conclusions
For Yii2 and Laravel teams, PDF invoices should be a data problem, not a layout problem.
Call generate-document, download the file, and ship the PDF — while designers iterate
templates in the portal.
Ready to drop mPDF from your stack? QuartzAPI is in public Beta: create a free account, grab an API key, and wire the examples above into your invoice controller.
Ready-to-use snippets
- Endpoint:
POST https://backend.quartzapi.com/index.php?r=api/v1-jobs/generate-documentwithtemplateCode+data. - Auth header:
Authorization: Bearer YOUR_API_KEY. - Download: use
result.downloadUrlorGET …/v1-documents/download&uid=…. - Full reference: Web API documentation.