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

Mpdf Bundle Laravel Package

bideogemu/mpdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require bideogemu/mpdf-bundle
    

    Ensure BideoGemu\MpdfBundle\BideoGemuMpdfBundle::class is enabled in config/bundles.php.

  2. First Use Case: Generate a PDF in a Laravel controller:

    use BideoGemu\MpdfBundle\Factory\MpdfFactory;
    
    public function generatePdf(MpdfFactory $mpdfFactory) {
        $mpdf = $mpdfFactory->createMpdfObject([
            'mode' => 'utf-8',
            'format' => 'A4',
        ]);
    
        $mpdf->WriteHTML($this->renderView('pdf.template.twig', ['data' => $data]));
        return $mpdfFactory->createDownloadResponse($mpdf, 'document.pdf');
    }
    
  3. Key Files to Review:

    • config/packages/bideogemu_mpdf.yaml (default config).
    • vendor/bideogemu/mpdf-bundle/src/Factory/MpdfFactory.php (factory logic).
    • Example Twig templates (e.g., resources/views/pdf/template.twig).

Implementation Patterns

Usage Patterns

  1. Factory-Based Instantiation: Always use MpdfFactory to create MPDF instances. Avoid direct instantiation of \Mpdf\Mpdf:

    // Good
    $mpdf = $mpdfFactory->createMpdfObject($customOptions);
    
    // Avoid
    $mpdf = new \Mpdf\Mpdf($options);
    
  2. Configuration Management:

    • Default Options: Define in config/packages/bideogemu_mpdf.yaml:
      bideogemu_mpdf:
          default_options:
              mode: utf-8
              format: A4
              margin_header: 5
              margin_footer: 5
      
    • Runtime Overrides: Merge with defaults via the factory:
      $mpdf = $mpdfFactory->createMpdfObject([
          'orientation' => 'L', // Overrides default
      ]);
      
  3. Twig Integration:

    • Render Twig templates to HTML before passing to MPDF:
      $html = $this->renderView('pdf.template.twig', ['data' => $data]);
      $mpdf->WriteHTML($html);
      
    • Use partials for headers/footers:
      $mpdf->SetHTMLHeader($this->renderView('pdf.header.twig'));
      
  4. Response Handling:

    • Download: Force download with:
      return $mpdfFactory->createDownloadResponse($mpdf, 'filename.pdf');
      
    • Inline Display: Stream directly:
      return $mpdfFactory->createStreamResponse($mpdf, 'filename.pdf');
      
  5. Queueing for Large PDFs: Use Laravel queues to avoid timeouts:

    GeneratePdfJob::dispatch($data)->onQueue('pdfs');
    

    Job example:

    public function handle() {
        $mpdf = $this->mpdfFactory->createMpdfObject([]);
        $mpdf->WriteHTML($this->renderView('pdf.template.twig', ['data' => $this->data]));
        Storage::put('pdfs/temp.pdf', $mpdf->Output('', 'S'));
    }
    

Workflows

  1. Dynamic PDF Generation:

    • Fetch data from a model, pass to Twig, and generate PDF in one flow:
      public function generateInvoice($invoiceId) {
          $invoice = Invoice::findOrFail($invoiceId);
          $mpdf = $this->mpdfFactory->createMpdfObject(['format' => 'A4']);
          $mpdf->WriteHTML($this->renderView('invoices/pdf.twig', ['invoice' => $invoice]));
          return $this->mpdfFactory->createDownloadResponse($mpdf, "invoice_{$invoiceId}.pdf");
      }
      
  2. Reusable PDF Components:

    • Create base Twig templates with blocks for headers/footers:
      {# resources/views/pdf/base.twig #}
      <!DOCTYPE html>
      <html>
          <head>
              {% block head %}{% endblock %}
          </head>
          <body>
              {% block content %}{% endblock %}
          </body>
      </html>
      
    • Extend for specific PDFs:
      {# resources/views/pdf/report.twig #}
      {% extends 'pdf/base.twig' %}
      {% block content %}
          {{ include('pdf/report_content.twig') }}
      {% endblock %}
      
  3. Testing:

    • Mock MpdfFactory in tests:
      $mockMpdf = Mockery::mock(\Mpdf::class);
      $mockMpdf->shouldReceive('WriteHTML')->once();
      $mockMpdf->shouldReceive('Output')->once()->andReturn('PDF_CONTENT');
      
      $factory = $this->app->make(MpdfFactory::class);
      $factory->shouldReceive('createMpdfObject')->andReturn($mockMpdf);
      

Integration Tips

  1. Laravel Service Provider: Bind the factory explicitly if autowiring fails:

    public function register() {
        $this->app->bind(MpdfFactory::class, function ($app) {
            return new MpdfFactory(
                $app['config']['mpdf.default_options'],
                storage_path('app/mpdf_cache')
            );
        });
    }
    
  2. Custom MPDF Extensions: Extend the factory to support custom MPDF classes:

    class CustomMpdfFactory extends MpdfFactory {
        protected function createMpdfInstance(array $options) {
            return new CustomMpdf($options);
        }
    }
    

    Register in config/services.php:

    'mpdf_factory' => \App\Services\CustomMpdfFactory::class,
    
  3. Environment-Specific Configs: Override defaults per environment:

    # config/packages/bideogemu_mpdf.yaml
    when@dev:
        default_options:
            format: Letter
    
  4. Caching: Cache compiled Twig templates for PDFs:

    $twig = $this->app->make(Twig::class);
    $twig->getLoader()->setCache($this->app['path.cache'].'/twig');
    

Gotchas and Tips

Pitfalls

  1. Configuration Merging:

    • Issue: Runtime options may silently override defaults without warning.
    • Fix: Explicitly log merged options:
      $options = array_merge($this->defaultOptions, $runtimeOptions);
      $this->logger->debug('MPDF options merged:', ['options' => $options]);
      
  2. Cache Directory Permissions:

    • Issue: MPDF fails silently if cache_dir is unwritable.
    • Fix: Set permissions and validate:
      $cacheDir = storage_path('app/mpdf_cache');
      if (!is_writable($cacheDir)) {
          mkdir($cacheDir, 0755, true);
      }
      
  3. Twig Autoloader Conflicts:

    • Issue: Twig templates may fail to load if the autoloader isn’t configured.
    • Fix: Ensure Twig is properly set up in Laravel:
      $this->app->register(TwigServiceProvider::class);
      
  4. Deprecated DI Arguments:

    • Issue: Older code may pass non-typed arguments to MpdfFactory.
    • Fix: Update constructor calls to use typed hints:
      // Old (may fail in v2.7+)
      new MpdfFactory($options);
      
      // New
      new MpdfFactory($defaultOptions, $cacheDir);
      
  5. Memory Limits:

    • Issue: Large PDFs may hit PHP’s memory_limit.
    • Fix: Increase limit or optimize templates:
      ini_set('memory_limit', '512M');
      

Debugging

  1. Enable MPDF Debugging: Add to config/packages/bideogemu_mpdf.yaml:

    debug: true
    

    Logs errors to storage/logs/mpdf.log.

  2. Check Output:

    • Issue: Blank PDFs often mean HTML rendering failed.
    • Debug: Output raw HTML to a file:
      file_put_contents('debug.html', $htmlContent);
      
  3. Symfony DI Errors:

    • Issue: ParameterNotFoundException for missing config.
    • Fix: Validate config/packages/bideogemu_mpdf.yaml exists and is loaded.
  4. Twig Errors:

    • Issue: Undefined variables in Twig templates.
    • Fix: Use {{ dump(data) }} in templates to debug variables.

Tips

  1. Default Options:
    • Centralize common options in config to avoid repetition:
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity