Skip to content

Getting output from a class

Class-based PDFs are designed to abstract away calls to stream, download and inline to cover 99% of use-cases, which would typically involve a scenario in which a PDF is generated and returned to the browser in a controller.

However, it's also possible to be explicit about it by calling the individual methods, just like you would on an Output instance.

No build-step

The first thing to note is that there is no build step when using the class-based approach. Builds are handled automatically, as and when needed.

Ineferred return (common use-case)

Once you have a PDF class ready to use, you can instantiate it and then return it in your controller.

php
use App\Models\TaxInvoice;
use App\PDFs\TaxInvoicePDF;

class ViewTaxInvoicePDF
{
  public function __invoke(TaxInvoice $invoice)
  {
    return new TaxInvoicePDF($invoice);
  }
}

This works because the base PDF class is Responsable, meaning that Laravel will call toResponse for you, and this method will automatically build and stream the PDF.

It is also possible to call toResponse manually.

php
$pdf = new TaxInvoicePDF($invoice);

return $pdf->toResponse($request);

Default stream mode

By default, returned class instances will stream inline to the browser.

If you want to force a download instead, then you need only override the streamMode method on your class:

php
use WeasyPrint\Enums\StreamMode;

class TaxInvoicePDF extends PDF
{
  // …

  public function streamMode(): StreamMode
  {
    return StreamMode::DOWNLOAD;
  }
}

Direct return

You can also call stream, download or inline directly:

php
use WeasyPrint\Enums\StreamMode;

$pdf = new TaxInvoicePDF($invoice);

return $pdf->stream(StreamMode::DOWNLOAD);
return $pdf->stream(StreamMode::INLINE);

// OR

return $pdf->download();
return $pdf->inline();

Released under the ISC License.