Installation:
composer require dol/mpdf-bundle
Enable the bundle in config/bundles.php:
return [
// ...
DarwinOnLine\MpdfBundle\DarwinOnLineMpdfBundle::class => ['all' => true],
];
Basic Usage:
Inject the Mpdf service into a controller or service:
use DarwinOnLine\MpdfBundle\Service\Mpdf;
class PdfController extends AbstractController
{
public function generatePdf(Mpdf $mpdf)
{
$mpdf->WriteHTML('<h1>Hello, PDF!</h1>');
return $mpdf->Output('output.pdf', 'D'); // 'D' forces download
}
}
First Use Case: Generate a simple PDF from a Twig template:
public function generateFromTwig(Mpdf $mpdf, $templatePath, array $data)
{
$html = $this->renderView($templatePath, $data);
$mpdf->WriteHTML($html);
return $mpdf->Output('document.pdf', 'I'); // 'I' sends inline
}
HTML-to-PDF Conversion:
WriteHTML() for raw HTML strings or Twig-rendered content.$mpdf->WriteHTML($this->renderView('pdf/template.html.twig', ['user' => $user]));
Styling and Layout:
WriteHTML() or SetCSS():
$mpdf->SetCSS('path/to/styles.css');
$mpdf->SetHeader('{PAGE_NUM}/{nb}');
Dynamic PDF Generation:
foreach ($items as $item) {
$mpdf->AddPage();
$mpdf->WriteHTML($this->renderView('pdf/item.html.twig', ['item' => $item]));
}
Integration with Symfony Forms:
WriteHTML():
$formView = $this->createFormView($form, $data);
$html = $this->render('form/_form.html.twig', ['form' => $formView]);
$mpdf->WriteHTML($html);
Custom Templates:
Mpdf service to add reusable methods:
// src/Service/CustomMpdf.php
class CustomMpdf extends Mpdf
{
public function generateInvoice($user, $items)
{
$this->AddPage();
$this->WriteHTML($this->renderView('pdf/invoice.html.twig', compact('user', 'items')));
}
}
services.yaml:
services:
App\Service\CustomMpdf:
decorates: 'darwin_online_mpdf.mpdf'
arguments: ['@darwin_online_mpdf.mpdf']
Asynchronous Generation:
$message = new GeneratePdfMessage($userId, $template);
$this->messageBus->dispatch($message);
Mpdf service.Caching:
$cacheKey = 'pdf_' . md5($template . serialize($data));
if (!$pdf = $this->cache->get($cacheKey)) {
$mpdf->WriteHTML($html);
$pdf = $mpdf->Output('', 'S'); // 'S' returns as string
$this->cache->set($cacheKey, $pdf, 3600); // Cache for 1 hour
}
Deprecated mPDF Methods:
Write()) may behave differently than v7+. Check mPDF’s migration guide.WriteHTML() for HTML content and Write() only for plain text.Font Issues:
fonts/ directory. If text appears as boxes:
var/log/dev.log for font-related errors.SetFont() or configure custom paths in config/packages/darwin_online_mpdf.yaml:
darwin_online_mpdf:
fonts_dir: '%kernel.project_dir%/public/fonts'
Memory Limits:
Allowed memory size of X bytes exhausted).memory_limit in php.ini or optimize HTML/CSS (e.g., inline CSS, avoid complex layouts).Twig Auto-escaping:
|raw filter:
{{ form|raw }}
$html = $this->renderView('template.html.twig', ['form' => $form], ['escape' => false]);
Output Modes:
Output() modes:
'D' (Download), 'I' (Inline), 'S' (Return as string), 'F' (Save to file).'S' for caching or further processing:
$pdfContent = $mpdf->Output('', 'S');
Inspect HTML:
WriteHTML():
file_put_contents('debug.html', $html);
debug.html in a browser to verify rendering.Log mPDF Errors:
$mpdf->debug = true;
$mpdf->error_policy = MPDF::ERROR_EXCEPTION;
Check Configuration:
config/packages/darwin_online_mpdf.yaml:
darwin_online_mpdf:
format: 'A4' # Default paper format
default_font: 'dejavu' # Ensure font exists
margin_top: 10
margin_bottom: 10
Custom mPDF Configuration:
Mpdf service to inject custom settings:
services:
DarwinOnLine\MpdfBundle\Service\Mpdf:
arguments:
$format: 'Letter'
$default_font: 'arial'
$margin_header: 20
$margin_footer: 20
Event Listeners:
// src/EventListener/PdfListener.php
class PdfListener implements KernelEventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', 20],
];
}
public function onKernelView(ViewEvent $event)
{
if ($event->getController() instanceof PdfController) {
// Modify $event->getControllerResult() before output
}
}
}
Symfony UX Turbo/Stimulus:
// assets/controllers/pdf_controller.js
import { Controller } from '@hotwired/stimulus';
export default class extends Controller {
generate() {
fetch('/pdf/generate', { method: 'POST' })
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
window.open(url);
});
}
}
Lazy Loading:
// Store data in session, generate PDF only when needed
$this->session->set('pdf_data', $data);
Batch Processing:
foreach ($users as $user) {
$this->messageBus->dispatch(new GeneratePdfMessage($user));
}
Minify HTML/CSS:
htmlmin or cssmin to reduce payload size before passing to WriteHTML().How can I help you explore Laravel packages today?