Prerequisites:
Installation:
composer require bideogemu/mpdf-bundle
First Use Case:
php artisan vendor:publish --provider="BideoGemu\MpdfBundle\MpdfBundle" --tag="config"
config/mpdf.php with your desired defaults (e.g., cache_dir, default_options).Mpdf service into a controller/service:
use Mpdf\Mpdf;
public function generatePdf(Mpdf $mpdf) {
$mpdf->writeHTML('<h1>Hello, Symfony 7!</h1>');
return $mpdf->output();
}
Note: The MpdfFactory now requires typed constructor arguments ($cacheDir, $defaultOptions), but these are auto-injected via Symfony’s DI container.1. Configuration Management:
Configuration.php tree to define hierarchical bundle options (e.g., nested default_options under mpdf).config/mpdf.php:
return [
'cache_dir' => storage_path('app/mpdf_cache'),
'default_options' => [
'mode' => 'utf-8',
'format' => 'A4',
],
];
MpdfFactory.2. Dependency Injection:
Mpdf and MpdfFactory are auto-wired. No manual binding needed.public function __construct(
private string $cacheDir,
private array $defaultOptions,
private MpdfFactory $factory
) {}
3. Bundle Integration:
config/bundles.php (Symfony 7 style):
return [
BideoGemu\MpdfBundle\MpdfBundle::class => ['all' => true],
];
4. PDF Generation Workflow:
// Controller/Service
public function generateInvoice(Mpdf $mpdf, array $customOptions) {
$mpdf->setOptions(array_merge($this->defaultOptions, $customOptions));
$mpdf->WriteHTML($this->renderInvoiceView());
return $mpdf->output('invoice.pdf', 'S'); // 'S' = send as attachment
}
Breaking Changes:
MpdfFactory now requires $cacheDir and $defaultOptions. If not provided, the bundle throws a ParameterNotFoundException.
config/mpdf.php is published and populated.bundles.php format is stricter. Laravel users may ignore this if the bundle auto-registers.Debugging Tips:
Mpdf throws InvalidArgumentException, verify cache_dir is writable and default_options is an array.php artisan debug:container to inspect service wiring.$mpdf->getOptions(); // Inspect merged config
Extension Points:
MpdfFactory to add pre-processing:
class CustomMpdfFactory extends MpdfFactory {
public function createCustomMpdf(): Mpdf {
$mpdf = parent::createMpdf();
$mpdf->setCompression(true);
return $mpdf;
}
}
Register it in services.yaml:
services:
App\Services\CustomMpdfFactory: ~
Mpdf\Mpdf: '@App\Services\CustomMpdfFactory'
kernel.request to modify Mpdf instances globally.Performance:
cache_dir to a dedicated storage path (e.g., storage_path('app/mpdf_cache')) to avoid permission issues.memory_limit. Increase it in .env:
MEMORY_LIMIT=1G
Laravel-Specific Notes:
@include('pdf.template') with ob_start()/ob_get_clean() to capture HTML before passing to Mpdf.$html = \Illuminate\Support\Facades\View::make('pdf.invoice')->render();
$mpdf->WriteHTML($html);
How can I help you explore Laravel packages today?