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 fetchRenderable- An object implementing theRenderableinterfaceSource- AWeasyPrint\Objects\Sourceinstance
Here's the method signature:
public function prepareSource(string|Renderable|Source $source): selfWhen 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:
$factory->prepareSource('<h1>Invoice</h1><p>Total: USD 100.00</p>');For longer HTML content, use a HEREDOC:
$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.
$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.
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:
$factory->prepareSource(
view('invoices.template', ['total' => 100.0])
);Source Object
For more control, use the Source class:
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):
$source = new Source('<h1>Invoice</h1>');
$source->addAttachment('/path/to/file.pdf');
$factory->prepareSource($source);Alternatively, add attachments after preparing the source:
$factory->prepareSource('<h1>Invoice</h1>')
->addAttachment('/path/to/file.pdf');