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

Print2Pdf Bundle Laravel Package

cravler/print2pdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cravler/print2pdf-bundle:dev-master
    

    Enable the bundle in config/bundles.php (required for Symfony < 4.4 or without Flex).

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

    use Cravler\Print2PdfBundle\Service\Print2Pdf;
    
    public function generatePdf(Print2Pdf $print2Pdf)
    {
        $pdf = $print2Pdf->generate('https://example.com', [
            'paper_width' => 8.5,
            'paper_height' => 11,
        ]);
        return new Response($pdf, 200, ['Content-Type' => 'application/pdf']);
    }
    
  3. Key Files:

    • src/Service/Print2Pdf.php: Core service class.
    • config/packages/cravler_print2pdf.yaml: Default configuration (if provided).

Implementation Patterns

Common Workflows

  1. URL-to-PDF Pipeline:

    // Controller
    public function generateInvoicePdf(Print2Pdf $print2Pdf, $invoiceUrl)
    {
        $pdf = $print2Pdf->generate($invoiceUrl, [
            'landscape' => true,
            'header_template' => $this->renderView('invoice_header.html.twig'),
        ]);
        return $this->file($pdf, 'invoice.pdf');
    }
    
  2. Dynamic HTML Generation:

    // Twig template: `invoice.html.twig`
    {{ render(controller('App\Controller\InvoiceController::generatePdfContent', {'id': invoice.id})) }}
    
    // Controller
    public function generatePdfContent($id)
    {
        $html = $this->renderView('invoice_content.html.twig', ['invoice' => $invoice]);
        return new Response($html);
    }
    
  3. Batch Processing:

    public function generateBulkPdfs(array $urls, array $options = [])
    {
        $print2Pdf = $this->container->get(Print2Pdf::class);
        return array_map(fn($url) => $print2Pdf->generate($url, $options), $urls);
    }
    

Integration Tips

  • Symfony Forms: Attach PDF generation to form submission:

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $pdf = $print2Pdf->generateFromHtml($form->createView(), ['paper_width' => 11]);
        $this->addFlash('success', 'PDF generated!');
        return $this->redirectToRoute('download_pdf', ['pdf' => base64_encode($pdf)]);
    }
    
  • Event Listeners: Trigger PDF generation on entity events (e.g., postPersist):

    public function onPostPersist(EntityManagerInterface $em, $entity)
    {
        if ($entity instanceof Invoice) {
            $pdf = $print2Pdf->generate($entity->getUrl());
            $entity->setPdf($pdf);
            $em->flush();
        }
    }
    
  • Queue Workers: Offload heavy PDF generation to a queue (e.g., Symfony Messenger):

    $message = new GeneratePdfMessage($url, $options);
    $this->messageBus->dispatch($message);
    

Gotchas and Tips

Pitfalls

  1. Dependency on go-print2pdf:

    • The bundle relies on a Go binary (go-print2pdf). Ensure it’s installed and accessible in your Docker container or server environment.
    • Fix: Include the Docker setup from the README or manually install the binary:
      go install github.com/cravler/go-print2pdf@latest
      
  2. Timeout Handling:

    • Default timeout: 0 means no timeout. Set a reasonable value (e.g., 30) for production:
      $print2Pdf->generate($url, ['timeout' => 30]);
      
  3. CSS/HTML Quirks:

    • Complex layouts (e.g., CSS Grid/Flexbox) may render poorly. Test with print_background: true if backgrounds are missing.
    • Workaround: Use @media print CSS rules for better control.
  4. Memory Limits:

    • Generating large PDFs may hit PHP memory limits. Increase memory_limit in php.ini or use chunked processing.

Debugging

  1. Check Binary Path:

    • If PDFs fail silently, verify the Go binary path:
      $print2Pdf->setBinaryPath('/path/to/go-print2pdf'); // Override if needed
      
  2. Log Errors:

    • Wrap calls in try-catch to log failures:
      try {
          $pdf = $print2Pdf->generate($url);
      } catch (\Exception $e) {
          $this->logger->error('PDF generation failed', ['error' => $e->getMessage()]);
      }
      
  3. Test Locally:

    • Use generateFromHtml() with static HTML to isolate issues:
      $html = file_get_contents('test.html');
      $pdf = $print2Pdf->generateFromHtml($html);
      

Extension Points

  1. Custom Templates:

    • Extend header/footer templates by overriding the bundle’s Twig templates (if provided) or passing dynamic HTML:
      $print2Pdf->generate($url, [
          'header_template' => $this->renderView('custom_header.html.twig'),
      ]);
      
  2. Post-Processing:

    • Chain with other libraries (e.g., setasign/fpdf) to add watermarks or signatures:
      $pdfContent = $print2Pdf->generate($url);
      $pdf = \FPDF::parse($pdfContent);
      $pdf->addPage();
      $pdf->write(0, 'Confidential');
      
  3. Configuration:

    • Override default options in config/packages/cravler_print2pdf.yaml:
      cravler_print2pdf:
          default_options:
              paper_width: 11
              paper_height: 17
              landscape: true
      
    • Access via service:
      $print2Pdf->generate($url); // Uses configured defaults
      
  4. Docker Optimization:

    • Cache the Go binary layer in Docker to speed up builds:
      FROM php:8.1 as builder
      RUN go install github.com/cravler/go-print2pdf@latest && \
          mv $(go env GOPATH)/bin/go-print2pdf /usr/local/bin/
      
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope