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

nucleos/dompdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nucleos/dompdf-bundle
    

    Ensure Nucleos\DompdfBundle\NucleosDompdfBundle::class is added to config/bundles.php.

  2. First Use Case: Generate a PDF from a Twig template in a controller:

    use Nucleos\DompdfBundle\Service\DompdfService;
    
    class PdfController extends AbstractController
    {
        public function generatePdf(DompdfService $dompdfService): Response
        {
            $html = $this->renderView('pdf/template.html.twig', [
                'data' => $this->fetchData(),
            ]);
    
            $pdf = $dompdfService->generate($html, 'filename.pdf');
            return new BinaryFileResponse($pdf, 200, [
                'Content-Type' => 'application/pdf',
                'Content-Disposition' => 'inline; filename="filename.pdf"',
            ]);
        }
    }
    
  3. Key Files:

    • config/packages/nucleos_dompdf.yaml (default config)
    • templates/pdf/ (store Twig templates here)
    • src/Service/DompdfService.php (customize if needed)

Implementation Patterns

Core Workflows

  1. Twig Integration: Use Twig templates for dynamic PDFs:

    {# templates/pdf/invoice.html.twig #}
    <html>
        <body>
            <h1>{{ invoice.title }}</h1>
            <table>
                {% for item in invoice.items %}
                    <tr><td>{{ item.name }}</td><td>{{ item.price }}</td></tr>
                {% endfor %}
            </table>
        </body>
    </html>
    
  2. Streaming Large PDFs:

    $dompdfService->stream($html, 'report.pdf');
    
  3. Customizing Options:

    # config/packages/nucleos_dompdf.yaml
    nucleos_dompdf:
        default_options:
            'defaultFont': 'DejaVu Sans'
            'isRemoteEnabled': true
            'isHtml5ParserEnabled': true
    
  4. Dependency Injection: Inject DompdfService into services for reusable PDF logic:

    class InvoiceService {
        public function __construct(private DompdfService $dompdf) {}
    
        public function generateInvoicePdf(Invoice $invoice): string {
            $html = $this->renderInvoiceTwig($invoice);
            return $this->dompdf->generate($html, 'invoice.pdf');
        }
    }
    
  5. Queueing PDF Jobs: Use Symfony Messenger to offload PDF generation:

    use Nucleos\DompdfBundle\Message\GeneratePdfMessage;
    
    $bus->dispatch(new GeneratePdfMessage(
        $html,
        'queued_report.pdf',
        new \DateTimeImmutable()
    ));
    

Gotchas and Tips

Common Pitfalls

  1. Memory Limits:

    • Large PDFs may hit PHP’s memory_limit. Increase it temporarily:
      ini_set('memory_limit', '512M');
      
    • Use stream() instead of generate() for large files to avoid memory spikes.
  2. Font Issues:

    • Ensure required fonts (e.g., DejaVu Sans) are installed on the server. Configure in nucleos_dompdf.yaml:
      nucleos_dompdf:
          fonts:
              - '%kernel.project_dir%/vendor/dompdf/dompdf/lib/fonts/DejaVuSans.ttf'
      
  3. CSS Inlining:

    • Dompdf renders external CSS poorly. Use inline styles or embed CSS in the HTML:
      <style>
          @import url('https://fonts.googleapis.com/css?family=Roboto');
          body { font-family: 'Roboto', sans-serif; }
      </style>
      
  4. Debugging:

    • Enable debug mode to log errors:
      nucleos_dompdf:
          debug: true
      
    • Check logs in var/log/dev.log for rendering issues.
  5. Caching:

    • Disable caching during development:
      nucleos_dompdf:
          options:
              'isRemoteEnabled': false
              'isPhpEnabled': false
      

Pro Tips

  1. Reuse PDF Logic: Create a base service for common PDF operations:

    class BasePdfService {
        public function __construct(private DompdfService $dompdf) {}
    
        protected function renderWithLayout(string $template, array $data): string {
            return $this->dompdf->render($this->renderView(
                'pdf/layouts/base.html.twig',
                ['content' => $this->renderView($template, $data)]
            ));
        }
    }
    
  2. Dynamic Filenames: Use uniqid() to avoid filename collisions:

    $filename = 'report_' . uniqid() . '.pdf';
    
  3. Testing: Mock DompdfService in PHPUnit:

    $this->dompdf
        ->expects($this->once())
        ->method('generate')
        ->with($html, 'test.pdf')
        ->willReturn(file_get_contents(__DIR__ . '/fixtures/test.pdf'));
    
  4. Headless Chrome Rendering: For complex layouts, pre-render HTML with Puppeteer and pass it to Dompdf:

    $html = $puppeteer->render('https://example.com/complex-page');
    $pdf = $dompdfService->generate($html, 'complex.pdf');
    
  5. Extension Points:

    • Override DompdfService to add pre/post-processing:
      class CustomDompdfService extends DompdfService {
          public function generate(string $html, string $filename): string {
              $html = $this->addWatermark($html);
              return parent::generate($html, $filename);
          }
      }
      
    • Register as a service in config/services.yaml:
      services:
          Nucleos\DompdfBundle\Service\DompdfService: '@custom_dompdf_service'
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle