Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Html2Pdf Bundle Laravel Package

carlescliment/html2pdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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
    
  2. 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
        }
    }
    

Where to Look First

  • Service Configuration: Check config/packages/config.yml for host/port settings.
  • Twig Templates: Ensure templates are optimized for PDF rendering (avoid complex CSS/JS).
  • Service Documentation: Html2Pdf REST Service for advanced options.

Implementation Patterns

Core Workflow

  1. Template Rendering: Use Twig to generate HTML dynamically:

    $html = $this->renderView('template.html.twig', ['variable' => $data]);
    
  2. 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
        ]
    );
    
  3. 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());
    

Integration Tips

  • 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');
    }
    

Gotchas and Tips

Pitfalls

  1. Service Unavailability:

    • The bundle relies on an external REST service. If html2pdf.mydomain.com is down, PDF generation will fail.
    • Fix: Implement a fallback (e.g., local DOMPDF) or retry logic.
  2. CSS/JS Limitations:

    • Complex CSS (e.g., @media print queries) or client-side JS may not render correctly in PDFs.
    • Fix: Use inline styles or PDF-specific CSS frameworks like PDFObject.
  3. Large HTML Payloads:

    • Sending massive HTML strings may exceed the service’s payload limits.
    • Fix: Stream the HTML or split into chunks.
  4. Configuration Overrides:

    • Bundle parameters (html2pdf.host, html2pdf.port) are not environment-aware by default.
    • Fix: Use Symfony’s %env% or Laravel’s .env for dynamic configuration:
      parameters:
          html2pdf.host: '%env(HTML2PDF_HOST)%'
      

Debugging

  • 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
    

Extension Points

  1. Custom Options: Extend the bridge to support additional options:

    // In a custom service
    $pdf = $this->bridge->getFromHtml($html, 'file.pdf', [
        'custom-option' => 'value',
    ]);
    
  2. 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;
        }
    }
    
  3. 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']);
            }
        }
    }
    

Performance Tips

  • 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));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge