Skip to content

Class-based Sources

WeasyPrint for Laravel also provides an object-oriented approach to PDF generation through classes, which serve as a dedicated place for encapsulating PDF-specific logic, enabling cleaner code organisation and making way for re-usability in different contexts of your application without needing to create abstraction layers of your own.

To define a PDF class, it need only extend the PDF abstract shipped with the package:

Basic Class

php
use Illuminate\Contracts\Support\Renderable;
use WeasyPrint\PDF;

class MyPDF extends PDF
{
  public function source(): Renderable
  {
    return view('my-pdf');
  }

  public function filename(): string
  {
    return 'my-pdf.pdf';
  }
}

A valid class is one that implements both the source and filename abstract methods, the signatures of which are:

php
use Illuminate\Contracts\Support\Renderable;
use WeasyPrint\Objects\Source;

abstract public function source(): Source|Renderable|string;
abstract public function filename(): string;

Much like basic sources, the class source must be an instance of Source or Renderable, or must otherwise be a pre-rendered string.

Specific return types

The return type does not need to match the abstract signature, and it’s recommended to only indicate what is actually being returned from your implementation. For example, if you are returning a pre-rendered string, then use string as the return type.

A filename is always required. You can customise this at runtime, perhaps using some value passed into a constructor (see below).

Class with custom logic

If you want to implement custom logic in your PDF class, based on data from the outside, then you should introduce a constructor that makes that data available to it.

For example:

php
use App\Models\TaxInvoice;
use Illuminate\Contracts\Support\Renderable;
use WeasyPrint\PDF;

class TaxInvoicePDF extends PDF
{
  public function __construct(
    public readonly TaxInvoice $invoice,
  ) {}

  public function source(): Renderable
  {
    return view('accounts.tax-invoice', [
      'invoice' => $this->invoice
    ]);
  }

  public function filename(): string
  {
    return sprintf(
      '%d-%s.pdf',
      $this->invoice->id,
      str($this->invoice->debtor_name)->slug()->toString()
    );
  }
}

Custom config

If you want to configure the underlying service instance before it is created, then you can add a config method that behaves like tapConfig to your class. This is documented in the configuration section.

Released under the ISC License.