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

94noni/html2pdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require 94noni/html2pdf-bundle
    

    Enable the bundle in config/bundles.php:

    Noni\Html2pdfBundle\NoniHtml2pdfBundle::class => ['all' => true],
    
  2. First Use Case: Inject Html2pdfFactory into a service/controller and generate a PDF:

    use Noni\Html2pdfBundle\Factory\Html2pdfFactory;
    
    class InvoiceController extends AbstractController
    {
        public function __construct(private Html2pdfFactory $factory) {}
    
        public function generatePdf(): Response
        {
            $html = $this->renderView('invoice/pdf.html.twig');
            $pdf = $this->factory->create()->fromHtml($html)->output();
            return new BinaryFileResponse($pdf, 200, ['Content-Type' => 'application/pdf']);
        }
    }
    
  3. Key Files:

    • config/packages/noni_html2pdf.yaml (for customization)
    • Twig templates (e.g., invoice/pdf.html.twig) for HTML content.

Implementation Patterns

Core Workflow

  1. HTML Generation: Use Twig templates (*.html.twig) to structure PDF content. Example:

    {# invoice/pdf.html.twig #}
    <html>
        <body>
            <h1>Invoice #{{ invoice.number }}</h1>
            <table>
                {% for item in invoice.items %}
                    <tr><td>{{ item.description }}</td><td>{{ item.price }}</td></tr>
                {% endfor %}
            </table>
        </body>
    </html>
    
  2. PDF Creation:

    // Controller/Service
    $html = $this->renderView('invoice/pdf.html.twig', ['invoice' => $invoice]);
    $pdf = $this->factory
        ->create('P', 'A4', 'en', true, 'UTF-8', [10, 15, 10, 15])
        ->fromHtml($html)
        ->output();
    
  3. Response Handling:

    return new BinaryFileResponse(
        $pdf,
        200,
        ['Content-Disposition' => 'attachment; filename="invoice.pdf"']
    );
    

Integration Tips

  • Dynamic Content: Pass data to Twig templates via controller/service methods.
  • Reusable Services: Create a dedicated PdfGenerator service to encapsulate logic:
    class PdfGenerator
    {
        public function __construct(private Html2pdfFactory $factory) {}
    
        public function generate(string $template, array $data, array $options = []): string
        {
            $html = $this->renderView($template, $data);
            $pdf = $this->factory->create(...$options)->fromHtml($html);
            return $pdf->output();
        }
    }
    
  • Configuration Overrides: Use config/packages/noni_html2pdf.yaml to set defaults:
    noni_html2pdf:
        orientation: 'L'  # Default landscape
        margin: [20, 20, 20, 20]
    

Gotchas and Tips

Pitfalls

  1. Abandoned Package:

    • No active maintenance; fork or extend locally if critical bugs arise.
    • Monitor for breaking changes in underlying spipu/html2pdf.
  2. CSS Limitations:

    • Complex CSS (e.g., flexbox, grid) may render poorly. Use tables or inline styles for reliability.
    • Test with html2pdf's CSS support docs.
  3. Memory Issues:

    • Large HTML content may cause timeouts. Optimize templates or chunk generation.
  4. Dependency Conflicts:

    • Ensure spipu/html2pdf (v6+) is installed as a dev dependency if extending:
      composer require spipu/html2pdf --dev
      

Debugging

  • Log HTML: Output raw HTML before conversion to debug rendering:
    file_put_contents('debug.html', $html);
    
  • Check Options: Validate Html2pdf options with:
    $pdf = $this->factory->create('P', 'A4'); // Explicit defaults
    
  • Error Handling: Wrap PDF generation in try-catch:
    try {
        $pdf = $this->factory->create()->fromHtml($html);
    } catch (\Exception $e) {
        $this->addFlash('error', 'PDF generation failed: ' . $e->getMessage());
        return $this->redirectToRoute('home');
    }
    

Extension Points

  1. Custom Factories: Extend Html2pdfFactory to add project-specific defaults:

    class CustomHtml2pdfFactory extends Html2pdfFactory
    {
        protected function getDefaultOptions(): array
        {
            return array_merge(parent::getDefaultOptions(), [
                'defaultHeader' => $this->renderView('pdf/header.html.twig'),
                'defaultFooter' => $this->renderView('pdf/footer.html.twig'),
            ]);
        }
    }
    

    Register as a service in config/services.yaml:

    services:
        App\Service\CustomHtml2pdfFactory: '@noni_html2pdf.factory.custom'
    
  2. Event Listeners: Hook into Symfony events (e.g., kernel.response) to auto-generate PDFs:

    // src/EventListener/PdfListener.php
    class PdfListener
    {
        public function onKernelResponse(FilterResponseEvent $event): void
        {
            if ($event->getRequest()->attributes->get('pdf')) {
                $response = new BinaryFileResponse($this->generatePdf());
                $event->setResponse($response);
            }
        }
    }
    
  3. Twig Extensions: Add a Twig function for inline PDF generation:

    // src/Twig/AppExtension.php
    class AppExtension extends AbstractExtension
    {
        public function getFunctions(): array
        {
            return [
                new TwigFunction('generate_pdf', [$this->factory, 'create']),
            ];
        }
    }
    

    Usage in Twig:

    {{ generate_pdf('P', 'A4')->fromHtml(content).output() }}
    
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
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