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

Pdf Report Bundle Laravel Package

discustecnologia/pdf-report-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies Ensure wkhtmltopdf is installed on your system (Linux/macOS: sudo apt-get install wkhtmltopdf or brew install wkhtmltopdf; Windows: download from wkhtmltopdf.org). Add the bundle via Composer:

    composer require discustecnologia/pdf-report-bundle
    
  2. Enable the Bundle Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    DiscusTecnologia\PdfReportBundle\DiscusTecnologiaPdfReportBundle::class => ['all' => true],
    
  3. First Use Case: Generate a Simple PDF In a controller, inject the service and generate a PDF from a Twig template:

    use Symfony\Component\HttpFoundation\Response;
    
    public function generateReportAction()
    {
        $pdfReport = $this->get('discus-tecnologia.pdf-report');
        $pdfReport->addPages('default/report.twig', ['data' => 'Hello, PDF!']);
        return $pdfReport->generate();
    }
    

    Create a Twig template at templates/default/report.twig:

    <h1>My Report</h1>
    <p>{{ data }}</p>
    

Implementation Patterns

Core Workflow

  1. Template Structure

    • Use Twig templates for PDF content (e.g., templates/default/header.twig, templates/default/footer.twig).
    • Leverage Twig’s pdfReportPageNumber and pdfReportTotalPages variables for pagination logic (e.g., multi-page reports).
    • Example pagination snippet (from README):
      {% for i in ((pdfReportPageNumber -1) * 4)..(((pdfReportPageNumber * 4)-1) < (obj|length - 1) ? ((pdfReportPageNumber * 4)-1) : obj|length-1) %}
          <div>{{ obj[i] }}</div>
      {% endfor %}
      
  2. Dynamic Data Binding Pass data to templates via addPages():

    $pdfReport->addPages('default/invoice.twig', [
        'invoice' => $invoiceData,
        'client'  => $clientData,
    ]);
    
  3. Styling and Layout

    • Use CSS in Twig templates (e.g., style="page-break-after: always;" for page breaks).
    • Set margins, headers, and footers programmatically:
      $pdfReport->setMargins(10, 10, 10, 10); // top, right, bottom, left
      $pdfReport->setHeader('default/header.twig');
      $pdfReport->setFooter('default/footer.twig');
      
  4. Integration with Forms/Entities

    • Fetch data from Doctrine entities or forms:
      $users = $this->getDoctrine()->getRepository(User::class)->findAll();
      $pdfReport->addPages('default/user_list.twig', ['users' => $users]);
      
    • Use Twig’s batch filter for chunking data (e.g., 10 records per page):
      {% for user in users|batch(10, 'page') %}
          {# Render user data #}
      {% endfor %}
      
  5. Streaming Large PDFs For large datasets, stream the PDF to avoid memory issues:

    $response = new Response();
    $response->headers->set('Content-Type', 'application/pdf');
    $pdfReport->generate()->stream($response);
    return $response;
    

Gotchas and Tips

Pitfalls

  1. wkhtmltopdf Path Issues

    • If PDF generation fails, ensure wkhtmltopdf is in your PATH or configure the bundle’s path:
      # config/packages/discus_tecnologia_pdf_report.yaml
      discus_tecnologia_pdf_report:
          wkhtmltopdf_path: '/usr/local/bin/wkhtmltopdf'
      
  2. Twig Template Caching

    • Clear Twig cache if templates aren’t updating:
      php bin/console cache:clear
      
  3. CSS/HTML Limitations

    • Avoid complex CSS (e.g., floats, flexbox) as wkhtmltopdf has limited support. Use tables or simple layouts.
    • Test templates with wkhtmltopdf directly to isolate issues:
      wkhtmltopdf input.html output.pdf
      
  4. Memory Limits

    • Large PDFs may hit PHP’s memory limit. Increase memory_limit in php.ini or stream the response.
  5. Deprecated Bundle

    • Last updated in 2017. Verify compatibility with your Symfony version (tested on Symfony 2/3). For Symfony 5/6, consider alternatives like knplabs/knp-snappy.

Debugging Tips

  1. Check wkhtmltopdf Logs Run wkhtmltopdf manually with verbose output:

    wkhtmltopdf -q input.html output.pdf
    
  2. Inspect Generated HTML Save the Twig-rendered HTML to a file for debugging:

    $html = $this->renderView('default/report.twig', ['data' => $data]);
    file_put_contents('debug.html', $html);
    
  3. Common Errors

    • "Command not found": wkhtmltopdf not installed or not in PATH.
    • Blank PDF: Empty Twig template or missing data.
    • Layout issues: Use inline styles or simple CSS (avoid external sheets).

Extension Points

  1. Customize wkhtmltopdf Options Override default options via config:

    discus_tecnologia_pdf_report:
        options:
            enable-javascript: true
            print-media-type: true
    
  2. Add Custom Headers/Footers Extend the bundle by creating a custom service:

    // src/Service/CustomPdfReport.php
    class CustomPdfReport extends \DiscusTecnologia\PdfReportBundle\Service\PdfReport
    {
        public function addCustomHeader($template) {
            $this->setHeader($template);
            // Add custom logic
        }
    }
    

    Register as a service in services.yaml:

    services:
        App\Service\CustomPdfReport:
            decorates: 'discus-tecnologia.pdf-report'
            arguments: ['@discus-tecnologia.pdf-report.inner']
    
  3. Use with API Platform For API-driven PDFs, create a custom action:

    use ApiPlatform\Core\Action\ContextAwareActionTrait;
    
    class GeneratePdfAction
    {
        use ContextAwareActionTrait;
    
        public function __invoke($data, UrlGeneratorInterface $urlGenerator) {
            $pdfReport = $this->container->get('discus-tecnologia.pdf-report');
            $pdfReport->addPages('default/api_report.twig', ['data' => $data]);
            return $pdfReport->generate();
        }
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky