Sunday, May 19, 2024
HomePHPSimply create PDFs in Laravel apps

Simply create PDFs in Laravel apps


We’ve launched a brand new bundle referred to as spatie/laravel-pdf, a batteries-included bundle to generate PDFs in Laravel apps. Below the hood, it makes use of Chromium to generate PDFs from Blade views. You should use fashionable CSS options like grid, flexbox, and even frameworks like Tailwind to create stunning PDFs.

On this put up, I’d wish to introduce and show the bundle.

Creating PDFs

As soon as the bundle has been put in, you should utilize the PDF facade to create PDFs. The premise for PDF creation is HTML, and the simplest approach to generate HTML in a Laravel app is through the use of a view.

Here is an instance of making a PDF from a Blade view.

use SpatieLaravelPdfFacadesPdf;

Pdf::view('pdf.bill')->save('/some/listing/bill.pdf');

Below the hood, the bundle will, through Browsershot, spin up an occasion of Chrome, load your HTML, and let Chrome save a PDF. As a result of Chrome has a state-of-the-art rendering engine, you need to have the ability to use fashionable CSS options to create your PDF.

As a second parameter, you’ll be able to cross an array of knowledge that can be made out there within the view. You would possibly use that to cross an Eloquent mannequin, equivalent to an bill, to the view.

use SpatieLaravelPdfFacadesPdf;

Pdf::view('pdf.bill', ['invoice' => $invoice])
   ->save('/some/listing/bill.pdf');

Along with saving regionally, you possibly can save your PDF on any of your configured disks.

Here is an instance of saving a PDF to the s3 disk.

use SpatieLaravelPdfFacadesPdf;

Pdf::view('bill')
   ->disk('s3')
   ->save('invoice-april-2022.pdf');

As a substitute of utilizing a Blade view, you can too create a PDF from a string of HTML.

use SpatieLaravelPdfFacadesPdf;

Pdf::html('<h1>Hiya world!!</h1>')->save('/some/listing/bill.pdf');

Responding with PDFs

In a controller, you’ll be able to create and return a PDF utilizing the pdf() perform.

use perform SpatieLaravelPdfSupportpdf;

class DownloadInvoiceController
{
    public perform __invoke(Bill $bill)
    {
        return pdf()
            ->view('pdf.bill', compact('bill'))
            ->title('invoice-2023-04-10.pdf');
    }
}

By default, the PDF can be inlined within the browser. Which means the PDF can be displayed within the browser if the
browser helps it. If the consumer tries to obtain the PDF, will probably be named “invoice-2023-04-10.pdf”. We advocate that
you at all times title your PDFs.

You should use the obtain() technique to power the PDF to be downloaded.

use perform SpatieLaravelPdfSupportpdf;

class DownloadInvoiceController
{
    public perform __invoke(Bill $bill)
    {
        return pdf()
            ->view('pdf.bill', compact('bill'))
            ->title('invoice-2023-04-10.pdf')
            ->obtain();
    }
}

Utilizing JavaScript

The JavaScript in your HTML can be executed by Chrome when the PDF is created. You could possibly use this to have a JavaScript charting library render a chart.

Here is a easy instance. When you’ve got this Blade view…

<div id="goal"></div>

<script>
    doc.getElementById('goal').innerHTML = 'whats up';
</script>

… and render it with this code…

use SpatieLaravelPdfFacadesPdf;

Pdf::view('your-view')->save($pathToPdf);

… the textual content whats up can be seen within the PDF.

Testing PDFs

Producing a PDF could be gradual, as a whole occasion of Chrome must be began. In your checks, this slowness could be bothersome. That’s why the bundle ships with a PDF pretend. No PDF technology will happen when utilizing this pretend, and your checks will run quicker.

// in your take a look at

use SpatieLaravelPdfFacadesPdf;

beforeEach(perform () {
    Pdf::pretend();
});

When PDF technology is faked, you should utilize some highly effective assertion strategies.

You should use the assertSaved technique to claim {that a} PDF was saved with particular properties. You must cross it a callable which can obtain an occasion of SpatieLaravelPdfPdfBuilder. If the callable returns true, the assertion will cross.

use SpatieLaravelPdfFacadesPdf;
use SpatieLaravelPdfPdfBuilder;

Pdf::assertSaved(perform (PdfBuilder $pdf) {
    return $pdf->downloadName === 'bill.pdf'
        && str_contains($pdf->html, 'Your complete for April is $10.00'));
});

The assertRespondedWithPdf technique can be utilized to claim {that a} PDF was generated and returned as a response.

Think about you have got this route:

use SpatieLaravelPdfFacadesPdf;

Route::get('download-invoice', perform () {
    return pdf('pdf.bill')->obtain('invoice-for-april-2022.pdf');
});

In your take a look at for this route you should utilize the assertRespondedWithPdf to make sure that a PDF was generated and returned as a obtain. You may even make assertions on the content material of the PDF.

use SpatieLaravelPdfFacadesPdf;
use SpatieLaravelPdfPdfBuilder;

it('can obtain an bill', perform () {
    $this
        ->get('download-invoice')
        ->assertOk();
        
    Pdf::assertRespondedWithPdf(perform (PdfBuilder $pdf) {
        return $pdf->downloadName === 'invoice-for-april-2022.pdf'
            && $pdf->isDownload()
            && str_contains($pdf->html, 'Your complete for April is $10.00'));
    });
});

Producing PDFs on AWS Lambda

Producing PDFs regionally could be resource-intensive. When you’re having to generate a number of PDFs or having bother putting in the mandatory dependencies in your server, it’s possible you’ll need to think about using AWS Lambda to generate your PDFs.

To generate PDFs on AWS Lambda, you have to set up these two packages in your app.

With these two packages put in, you’ll be able to generate PDFs on AWS Lambda like this:

Pdf::view('pdf.bill', $information)
    ->generateOnLambda()
    ->save('bill.pdf');

If you wish to create all PDFs in your app on Lambda, you’ll be able to set it as a default like this:

// sometimes, in a service supplier

Pdf::default()->generateOnLambda();

In closing

I had enjoyable coding this bundle, and I hope you’ll take pleasure in utilizing it. There are a lot of choices that I didn’t cowl on this put up, equivalent to formatting PDFS, including headers and footers, utilizing web page breaks, and rather more!

Laravel PDF makes use of headless Chrome to generate PDFs. It is a nice resolution, as you should utilize any CSS you need, and will probably be rendered appropriately. Nevertheless, producing a PDF this manner could be resource-intensive. When you don’t like this trade-off, an excellent different to take a look at is laravel-dompdf.

Laravel PDF is only one of many packages that we have made. You may discover an in depth record of Laravel and PHP packages we launched beforehand on our firm web site. There’s in all probability one thing there to your subsequent undertaking. When you like our open-source stuff, be sure you additionally take a look at our paid merchandise that make engaged on open-source sustainable for our firm.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments