Guides / Generate PDFs in Laravel

Frameworks · Updated 2026-12-03

Generate PDFs in Laravel

This guide renders PDFs from Laravel with the built-in Http facade. You post a template id and an array of data to DevilPDF and get back the file or a link. There is no PHP PDF library to configure and no browser binary on your server, and the documents render in a current version of Chrome, so modern CSS and every script work.

The free plan includes 500 documents a month.

#1. Configure the key

Sign up, create a key under API keys, and add it to .env:

.env
DEVILPDF_API_KEY=dp_live_...

Expose it through config/services.php, so it still works after php artisan config:cache:

config/services.php
<?php

return [
    // ...your other services

    'devilpdf' => [
        'key' => env('DEVILPDF_API_KEY'),
    ],
];

#2. A small service class

app/Services/DevilPdf.php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class DevilPdf
{
    private const URL = 'https://devilpdf.com/v1/render';

    /** Render and return the PDF bytes. Nothing is stored at DevilPDF. */
    public function file(array $body): string
    {
        return Http::withToken(config('services.devilpdf.key'))
            ->timeout(60)
            ->post(self::URL, $body + ['output' => 'file'])
            ->throw()
            ->body();
    }

    /** Render and return the document: url, id, pages, expires_at. */
    public function document(array $body): array
    {
        return Http::withToken(config('services.devilpdf.key'))
            ->timeout(60)
            ->post(self::URL, $body)
            ->throw()
            ->json();
    }
}

withToken() sends Authorization: Bearer ..., and post() sends the array as JSON. throw() turns a 4xx or 5xx into an exception. The response body of a failed request holds {"error": {"type": "...", "message": "..."}}, so you can read the reason with $e->response->json('error.message').

#3. Return a PDF from a controller

app/Http/Controllers/InvoicePdfController.php
<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Services\DevilPdf;
use Illuminate\Support\Facades\Gate;

class InvoicePdfController extends Controller
{
    public function __invoke(Invoice $invoice, DevilPdf $pdf)
    {
        Gate::authorize('view', $invoice);

        $bytes = $pdf->file([
            'template' => 'invoice',
            'data' => [
                'number' => $invoice->number,
                'issue_date' => $invoice->issued_at->toDateString(),
                'currency' => $invoice->currency,
                'customer' => ['name' => $invoice->customer->name, 'address' => $invoice->customer->address],
                'items' => $invoice->lines->map(fn ($line) => [
                    'name' => $line->description,
                    'quantity' => $line->quantity,
                    'unit_price' => (float) $line->unit_price,
                ])->all(),
                'tax_rate' => 13,
                'tax_label' => 'HST',
            ],
        ]);

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

And the route:

routes/web.php
<?php

use App\Http\Controllers\InvoicePdfController;
use Illuminate\Support\Facades\Route;

Route::get('/invoices/{invoice}/pdf', InvoicePdfController::class)->middleware('auth');

The invoice starter adds up the line items, discount and tax, so you never send totals. Fetch GET /v1/templates/invoice to see every field it accepts. The other starters are quote, receipt, statement, report, packing-slip and certificate.

#Save it to a disk

To keep a copy on S3 or local storage, write the bytes with the Storage facade:

use Illuminate\Support\Facades\Storage;

$bytes = app(DevilPdf::class)->file(['template' => 'receipt', 'data' => $receiptData]);
Storage::disk('s3')->put("receipts/{$order->id}.pdf", $bytes);

On paid plans DevilPDF can also upload straight to your own bucket with "destination": "s3". See storage.

#Generate in a queued job

Sending a PDF by email after checkout should not hold up the response. Put the render in a job:

app/Jobs/SendReceipt.php
<?php

namespace App\Jobs;

use App\Mail\ReceiptMail;
use App\Models\Order;
use App\Services\DevilPdf;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;

class SendReceipt implements ShouldQueue
{
    use Queueable;

    public function __construct(public Order $order) {}

    public function handle(DevilPdf $pdf): void
    {
        $bytes = $pdf->file([
            'template' => 'receipt',
            'locale' => $this->order->locale,
            'data' => $this->order->toReceiptData(),
        ]);

        Mail::to($this->order->email)->send(new ReceiptMail($this->order, $bytes));
    }
}

In ReceiptMail, attach the bytes with Attachment::fromData(fn () => $this->pdf, 'receipt.pdf')->withMime('application/pdf'). toReceiptData() stands for your own method that builds the array.

The Queueable trait in one import is the Laravel 11 style. On Laravel 10, use the four traits a generated job lists (Dispatchable, InteractsWithQueue, Queueable, SerializesModels).

#Every language

locale switches the starter's labels, dates and number format, and ar, he, fa and ur mirror the page right to left. Fonts for every script are loaded for you, so Arabic, Chinese, Hindi and Thai text render without installing anything on your server.

$bytes = app(DevilPdf::class)->file([
    'template' => 'invoice',
    'locale' => 'ar',
    'data' => ['number' => 'INV-1002', 'currency' => 'SAR', 'items' => [
        ['name' => 'استشارات', 'quantity' => 3, 'unit_price' => 1250],
    ]],
]);

See languages and locales.

#Next steps