Installation: Add the bundle via Composer:
composer require carlescliment/html2pdf-bundle:dev-master
Register the bundle in AppKernel.php:
new carlescliment\Html2PdfServiceBundle\carlesclimentHtml2PdfServiceBundle(),
Configure the service host in config/packages/config.yml:
parameters:
html2pdf.host: http://html2pdf.mydomain.com
html2pdf.port: 80
First Use Case: Convert a Twig template to PDF in a controller:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class PdfController extends AbstractController
{
public function generatePdf()
{
$html = $this->renderView('AcmeBundle:Document:invoice.html.twig', [
'data' => $invoiceData
]);
$pdf = $this->get('html2pdf.bridge')->getFromHtml($html, 'invoice.pdf');
return $pdf; // Returns a PDF response
}
}
config/packages/config.yml for host/port settings.Template Rendering: Use Twig to generate HTML dynamically:
$html = $this->renderView('template.html.twig', ['variable' => $data]);
PDF Conversion: Pass HTML to the bridge service with optional metadata:
$pdf = $this->get('html2pdf.bridge')->getFromHtml(
$html,
'filename.pdf',
[
'footer-left' => 'Page {PAGE_NUM} of {PAGE_COUNT}',
'margin-top' => 20,
'margin-bottom' => 20
]
);
Response Handling: Return the PDF directly or save it to storage:
// Direct download
return $pdf;
// Save to filesystem
file_put_contents('path/to/file.pdf', $pdf->getContent());
Dependency Injection: Inject the bridge service into controllers/services for reusability:
use carlescliment\Html2PdfServiceBundle\Bridge\Html2PdfBridge;
class PdfService {
private $bridge;
public function __construct(Html2PdfBridge $bridge) {
$this->bridge = $bridge;
}
}
Batch Processing: Queue PDF generation for large datasets using Symfony Messenger or Laravel Queues:
$this->get('messenger')->dispatch(new GeneratePdfJob($html, 'filename.pdf'));
Dynamic Filenames: Use timestamps or UUIDs to avoid conflicts:
$filename = 'invoice_' . uniqid() . '.pdf';
Error Handling: Wrap calls in try-catch to handle service unavailability:
try {
$pdf = $this->bridge->getFromHtml($html, $filename);
} catch (\Exception $e) {
$this->addFlash('error', 'Failed to generate PDF: ' . $e->getMessage());
return $this->redirectToRoute('home');
}
Service Unavailability:
html2pdf.mydomain.com is down, PDF generation will fail.CSS/JS Limitations:
@media print queries) or client-side JS may not render correctly in PDFs.Large HTML Payloads:
Configuration Overrides:
html2pdf.host, html2pdf.port) are not environment-aware by default.%env% or Laravel’s .env for dynamic configuration:
parameters:
html2pdf.host: '%env(HTML2PDF_HOST)%'
Log Requests: Enable debug mode to log the HTML and options sent to the service:
$this->get('logger')->debug('PDF HTML:', ['html' => substr($html, 0, 500)]);
Test Locally: Use a local instance of html2pdf-service for development:
parameters:
html2pdf.host: http://localhost:8080
Custom Options: Extend the bridge to support additional options:
// In a custom service
$pdf = $this->bridge->getFromHtml($html, 'file.pdf', [
'custom-option' => 'value',
]);
Response Transformation: Decorate the bridge to modify responses (e.g., add headers, compress):
class CustomPdfBridge extends Html2PdfBridge {
public function getFromHtml($html, $filename, array $options = []) {
$response = parent::getFromHtml($html, $filename, $options);
$response->headers->set('Content-Disposition', 'attachment; filename="custom_' . $filename . '"');
return $response;
}
}
Fallback Mechanism: Implement a fallback to a local library (e.g., Dompdf) if the service fails:
use Dompdf\Dompdf;
class FallbackPdfBridge {
public function getFromHtml($html, $filename, array $options = []) {
try {
return $this->get('html2pdf.bridge')->getFromHtml($html, $filename, $options);
} catch (\Exception $e) {
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->render();
return new Response($dompdf->output(), 200, ['Content-Type' => 'application/pdf']);
}
}
}
Cache Templates: Pre-render templates to HTML and cache them to avoid repeated processing:
$cachedHtml = $this->get('cache')->get('template_' . md5($data));
if (!$cachedHtml) {
$cachedHtml = $this->renderView('template.html.twig', ['data' => $data]);
$this->get('cache')->set('template_' . md5($data), $cachedHtml, 3600);
}
Async Generation: Use Symfony’s Messenger or Laravel Queues to offload PDF generation:
$this->get('messenger')->dispatch(new GeneratePdfJob($html, $filename, $options));
How can I help you explore Laravel packages today?