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

Dompdf Bundle Laravel Package

core23/dompdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nucleos/dompdf-bundle
    

    Ensure the bundle is enabled in config/bundles.php:

    return [
        // ...
        Nucleos\DompdfBundle\NucleosDompdfBundle::class => ['all' => true],
    ];
    
  2. Basic Usage: Inject the Dompdf service into a controller or service:

    use Nucleos\DompdfBundle\Service\Dompdf;
    
    class PdfController extends AbstractController
    {
        public function generatePdf(Dompdf $dompdf): Response
        {
            $dompdf->loadHtml('<h1>Hello, Dompdf!</h1>');
            $dompdf->render();
            return new Response($dompdf->getContent(), 200, [
                'Content-Type' => 'application/pdf',
                'Content-Disposition' => 'inline; filename="example.pdf"',
            ]);
        }
    }
    
  3. First Use Case: Generate a PDF from a Twig template:

    $dompdf->loadHtml($this->renderView('pdf/template.html.twig', ['data' => $data]));
    

Implementation Patterns

Common Workflows

  1. Dynamic PDF Generation: Use Twig templates for reusable PDF layouts:

    $html = $this->renderView('emails/invoice.html.twig', ['invoice' => $invoice]);
    $dompdf->loadHtml($html);
    
  2. Streaming PDFs: Stream PDFs directly to the browser without saving to disk:

    return new StreamedResponse(function () use ($dompdf) {
        echo $dompdf->getContent();
    }, 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'attachment; filename="report.pdf"',
    ]);
    
  3. Styling and Assets: Configure Dompdf to handle CSS and assets:

    # config/packages/nucleos_dompdf.yaml
    nucleos_dompdf:
        options:
            isRemoteEnabled: true
            isHtml5ParserEnabled: true
    
  4. Queueing PDF Jobs: Use Symfony Messenger to offload PDF generation:

    $this->messageBus->dispatch(new GeneratePdfJob($data, $template));
    

    Handler:

    public function __invoke(GeneratePdfJob $job, Dompdf $dompdf)
    {
        $dompdf->loadHtml($this->renderView($job->template, $job->data));
        return new Response($dompdf->getContent(), 200, [
            'Content-Disposition' => 'attachment; filename="job.pdf"',
        ]);
    }
    
  5. Customizing Headers/Footers: Use Dompdf’s built-in features or extend the bundle:

    $dompdf->getDompdf()->setOption('defaultFont', 'Arial');
    $dompdf->getDompdf()->setOption('isPhpEnabled', true);
    

Gotchas and Tips

Pitfalls

  1. CSS Limitations:

    • Dompdf has limited CSS3 support. Avoid complex layouts (e.g., flexbox, grid).
    • Use !important sparingly; Dompdf may not respect it as expected.
    • Fix: Simplify CSS or use inline styles where necessary.
  2. Memory Issues:

    • Generating large PDFs (e.g., multi-page reports) can exhaust memory.
    • Fix: Optimize HTML/CSS or increase PHP memory limit (memory_limit in php.ini).
  3. Asset Loading:

    • Remote assets (e.g., images from URLs) require isRemoteEnabled: true in config.
    • Fix: Configure nucleos_dompdf.options.isRemoteEnabled and ensure allow_url_fopen is enabled in php.ini.
  4. Twig Caching:

    • Cached Twig templates may cause stale PDFs if underlying data changes.
    • Fix: Clear cache or use flush() before rendering:
      $this->get('twig')->getEnvironment()->clearCacheFile($templatePath);
      
  5. Dependency Conflicts:

    • Dompdf may conflict with other packages using dompdf/dompdf.
    • Fix: Use composer why-not to resolve conflicts or pin versions in composer.json.

Debugging Tips

  1. Inspect HTML: Use Dompdf’s debug mode to see how HTML is rendered:

    $dompdf->getDompdf()->setOption('isDebugMode', true);
    

    Output will include warnings about unsupported CSS/HTML.

  2. Logging: Enable Dompdf logging to track issues:

    nucleos_dompdf:
        options:
            isDebugMode: true
    

    Check Symfony logs for Dompdf-related errors.

  3. Font Handling:

    • Dompdf requires fonts to be installed or bundled.
    • Fix: Use the font-metrics option to specify custom fonts:
      $dompdf->getDompdf()->setOption('fontDir', [__DIR__.'/fonts']);
      $dompdf->getDompdf()->setOption('fontCache', __DIR__.'/cache/fontcache');
      

Extension Points

  1. Custom Dompdf Configuration: Override default options via DI:

    services:
        Nucleos\DompdfBundle\Service\Dompdf:
            arguments:
                $options:
                    defaultFont: 'DejaVu Sans'
                    defaultFontSize: 10
    
  2. Event Listeners: Extend the bundle by listening to Dompdf events (e.g., pre-render hooks):

    $dompdf->getDompdf()->listen('pre_render', function ($dompdf) {
        $dompdf->setPaper('A4', 'portrait');
    });
    
  3. Service Decorators: Decorate the Dompdf service to add pre/post-processing:

    class CustomDompdfDecorator implements DompdfInterface
    {
        public function __construct(private DompdfInterface $dompdf) {}
    
        public function loadHtml(string $html): void
        {
            // Add custom logic (e.g., inject headers/footers)
            $this->dompdf->loadHtml($html);
        }
    }
    

    Register in services.yaml:

    services:
        Nucleos\DompdfBundle\Service\Dompdf:
            decorates: Nucleos\DompdfBundle\Service\Dompdf
            arguments:
                $dompdf: '@Nucleos\DompdfBundle\Service\Dompdf.inner'
    
  4. Command-Line Usage: Use the bundle in console commands for batch PDF generation:

    use Nucleos\DompdfBundle\Service\Dompdf;
    
    class GenerateBatchPdfCommand extends Command
    {
        public function __construct(private Dompdf $dompdf) {}
    
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $data = $this->fetchData();
            foreach ($data as $item) {
                $this->dompdf->loadHtml($this->renderView('batch_template.twig', ['item' => $item]));
                file_put_contents("pdf_{$item->id}.pdf", $this->dompdf->getContent());
            }
            return Command::SUCCESS;
        }
    }
    
  5. Testing: Mock the Dompdf service in tests to avoid rendering:

    $this->mockBuilder()
        ->disableOriginalConstructor()
        ->getMock()
        ->method('getContent')
        ->willReturn(file_get_contents(__DIR__.'/fixtures/test.pdf'));
    
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.
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
sandermuller/package-boost-php
sandermuller/boost-core
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle