Building the Output
Now that you know how to get a service class instance and prepare the source input, you are ready to build the output.
To do this, you can call the build()
method, which will return an instance of WeasyPrint\Objects\Output
.
$output = $service->build();
Using the output
The $output
object makes the following methods available:
stream
, download
and inline
use WeasyPrint\Enums\StreamMode;
public function stream(
string $filename,
array $headers = [],
StreamMode $streamMode,
): StreamedResponse;
This method creates a Symfony StreamedResponse
that may be used to download or inline the PDF to the client (such as a browser).
For example, in a controller:
use WeasyPrint\Facade as WeasyPrint;
use Symfony\Component\HttpFoundation\StreamedResponse;
use WeasyPrint\Enums\StreamMode;
public function __invoke(): StreamedResponse
{
$source = '<p>WeasyPrint rocks!</p>';
$service = WeasyPrint::prepareSource($source);
$output = $service->build();
return $output->stream(
'weasyprint-rocks.pdf',
headers: ['x-pdf' => 'weasyprint'] // just an example
streamMode: StreamMode::INLINE
);
}
You can also use the download
and inline
methods to achieve the same thing, without providing a StreamMode
directly. Both of these methods use the same signature as stream
, but exclude the streamMode
arguments.
Examples:
return $output->inline('weasyprint-rocks.pdf');
return $output->download('weasyprint-rocks.pdf');
Implicit Inference
If you would prefer to not call build()
, you can simply omit it and call the above methods directly on the service instance. For example:
WeasyPrint::prepareSource($source)->download('it-rocks.pdf')
putFile
This method forwards the data to Laravel’s Filesystem using the Storage
facade’s put
method, which gives you the ability to save the PDF to disk.
public function putFile(
string $path,
string|null $disk = null,
array $options = []
): bool;
getData
This method returns the raw PDF data as a string.
public function getData(): string;