Skip to content

Creating a Source

Now that you have a Factory instance, you can prepare a source.

Sources prepare and hold the HTML content that WeasyPrint will render into a PDF.

On your $factory instance, you can use the prepareSource() method, which accepts a single argument that can be one of the following types:

  • string - HTML content or a URL to fetch
  • Renderable - An object implementing the Renderable interface
  • Source - A WeasyPrint\Objects\Source instance

Here's the method signature:

php
public function prepareSource(string|Renderable|Source $source): self

When this method is called, it sets the source on the factory, ready to be built, and returns the factory.

HTML String

The simplest approach, pass HTML directly as a string:

php
$factory->prepareSource('<h1>Invoice</h1><p>Total: USD 100.00</p>');

For longer HTML content, use a HEREDOC:

php
$factory->prepareSource(<<<HTML
  <h1>Invoice</h1>
  <p>Total: USD 100.00</p>
HTML);

URL

You can also pass in a URL, which will be fetched and rendered into an HTML string.

php
$factory->prepareSource('https://example.com/invoice/123');

Renderable

You can also use a class that implements the Renderable contract from Laravel's Support library, which is already a dependency of this package. In this case, the render() method will be called automatically.

php
use Illuminate\Contracts\Support\Renderable;

class InvoiceTemplate implements Renderable
{
  public function __construct(private array $data) {}

  public function render(): string
  {
    $total = number_format($this->data['total'], 2);

    return <<<HTML
      <h1>Invoice</h1>
      <p>Total: USD $total</p>
    HTML;
  }
}

// Usage
$factory->prepareSource(new InvoiceTemplate(['total' => 100.0]));

Laravel Views implement Renderable, so you can pass them directly:

php
$factory->prepareSource(
  view('invoices.template', ['total' => 100.0])
);

Source Object

For more control, use the Source class:

php
use WeasyPrint\Objects\Source;

$source = new Source('<h1>Invoice</h1>');
$factory->prepareSource($source);

The Source class also supports attachments (files to include in the PDF):

php
$source = new Source('<h1>Invoice</h1>');
$source->addAttachment('/path/to/file.pdf');
$factory->prepareSource($source);

Alternatively, add attachments after preparing the source:

php
$factory->prepareSource('<h1>Invoice</h1>')
  ->addAttachment('/path/to/file.pdf');

Released under the ISC License.