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

Tcpdf Bundle Laravel Package

whiteoctober/tcpdf-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require whiteoctober/tcpdf-bundle
    

    For Symfony 3.4+, use the fork instead.

  2. Enable the Bundle: Add to AppKernel.php (Symfony < 4):

    new WhiteOctober\TCPDFBundle\WhiteOctoberTCPDFBundle(),
    

    For Symfony 4+, add to config/bundles.php:

    WhiteOctober\TCPDFBundle\WhiteOctoberTCPDFBundle::class => ['all' => true],
    
  3. First Use Case: Generate a basic PDF in a controller:

    use WhiteOctober\TCPDFBundle\TCPDF\TCPDF;
    use WhiteOctober\TCPDFBundle\TCPDF\TCPDFException;
    
    public function generatePdfAction()
    {
        $pdf = new TCPDF();
        $pdf->AddPage();
        $pdf->SetFont('helvetica', 'B', 20);
        $pdf->Cell(0, 10, 'Hello, TCPDF!', 0, 1, 'C');
        $pdf->Output('example.pdf', 'D'); // 'D' forces download
    }
    
  4. Where to Look First:

    • Bundle docs: GitHub README
    • TCPDF core docs: TCPDF Manual
    • Symfony Twig integration (if used): twig/tcpdf.html.twig templates in the bundle.

Implementation Patterns

Core Workflows

  1. PDF Generation in Controllers:

    public function generateInvoicePdf($invoiceId)
    {
        $pdf = new TCPDF();
        $pdf->AddPage();
        $pdf->SetFont('helvetica', '', 12);
    
        // Fetch invoice data (e.g., from Doctrine)
        $invoice = $this->getDoctrine()->getRepository(Invoice::class)->find($invoiceId);
    
        // Write data to PDF
        $pdf->Cell(0, 10, 'Invoice #'.$invoice->getNumber(), 0, 1, 'L');
        $pdf->Ln(10);
        $pdf->writeHTML($this->renderView('Invoice/pdf_content.html.twig', ['invoice' => $invoice]), true, false, true);
    
        return $pdf->Output('invoice_'.$invoiceId.'.pdf', 'D');
    }
    
  2. Twig Integration (if using Twig):

    • Create a Twig template (e.g., templates/Invoice/pdf_content.html.twig):
      <table>
          <tr><td>Customer:</td><td>{{ invoice.customer.name }}</td></tr>
          <tr><td>Amount:</td><td>{{ invoice.amount }} €</td></tr>
      </table>
      
    • Render in controller:
      $html = $this->renderView('Invoice/pdf_content.html.twig', ['invoice' => $invoice]);
      $pdf->writeHTML($html, true, false, true);
      
  3. Reusable PDF Services: Create a service to encapsulate PDF logic:

    # config/services.yaml
    services:
        App\Service\PdfGenerator:
            arguments:
                $tcpdf: '@white_october_tcpdf.tcpdf'
    
    // src/Service/PdfGenerator.php
    class PdfGenerator {
        private $tcpdf;
    
        public function __construct(TCPDF $tcpdf) {
            $this->tcpdf = $tcpdf;
        }
    
        public function generateFromHtml(string $html, string $filename): string {
            $this->tcpdf->AddPage();
            $this->tcpdf->writeHTML($html);
            return $this->tcpdf->Output($filename, 'S'); // 'S' returns as string
        }
    }
    
  4. Streaming PDFs: Return PDF as a stream (e.g., for APIs):

    public function streamPdfAction()
    {
        $pdf = new TCPDF();
        $pdf->AddPage();
        $pdf->SetFont('helvetica', '', 12);
        $pdf->Cell(0, 10, 'Streamed PDF', 0, 1, 'C');
    
        return new StreamedResponse(
            function () use ($pdf) {
                $pdf->Output('streamed.pdf', 'S');
            },
            200,
            ['Content-Type' => 'application/pdf']
        );
    }
    
  5. Dynamic Styling: Use TCPDF methods for dynamic styling:

    $pdf->SetFont('helvetica', 'B', 14); // Bold, size 14
    $pdf->SetTextColor(0, 0, 255); // Blue text
    $pdf->SetDrawColor(255, 0, 0); // Red borders
    $pdf->Rect(10, 10, 50, 10, 'D'); // Draw a red box
    

Integration Tips

  • Doctrine Integration: Fetch entities and loop through collections:
    foreach ($invoice->getItems() as $item) {
        $pdf->Cell(0, 10, $item->getDescription(), 0, 1);
        $pdf->Cell(0, 10, sprintf('%.2f €', $item->getPrice()), 0, 1, 'R');
    }
    
  • Assets (Images/Fonts): Load custom fonts or images:
    $pdf->AddTTFFont('path/to/font.ttf', 'TrueTypeUnicode', '', 32);
    $pdf->Image('path/to/image.png', 15, 15, 20, '', 'PNG');
    
  • Headers/Footers: Use TCPDF's built-in methods:
    $pdf->SetHeaderData('path/to/logo.png', 20, 'Title', 'Subtitle');
    $pdf->SetFooterData(['Title', 'Page'], PDF_PAGE_COUNT);
    $pdf->SetFooterMargin(10);
    

Gotchas and Tips

Common Pitfalls

  1. Font Issues:

    • TCPDF requires fonts to be in a specific format (e.g., .ttf for TrueType).
    • Fix: Use AddTTFFont() with the correct path and encoding.
    • Tip: Pre-load fonts in a service constructor to avoid repeated calls.
  2. Memory Limits:

    • Large PDFs (e.g., multi-page reports) may hit PHP memory limits.
    • Fix: Increase memory_limit in php.ini or optimize PDF generation (e.g., use writeHTML() for complex layouts instead of Cell()).
  3. Encoding Problems:

    • Special characters (e.g., é, ü) may render incorrectly.
    • Fix: Set the correct encoding:
      $pdf->SetFont('helvetica', '', '', 'win1252'); // or 'utf-8'
      
  4. Caching:

    • TCPDF caches fonts and resources. Clear cache if fonts/images change:
      $pdf->setFontCache('path/to/cache/dir');
      
  5. Deprecated Methods:

    • TCPDF v6+ deprecated some methods (e.g., AddPage() without parameters).
    • Tip: Check TCPDF changelog for breaking changes.
  6. Symfony 4+ Autowiring:

    • The bundle may not autowire TCPDF by default. Use:
      services:
          App\Service\PdfService:
              arguments:
                  $tcpdf: '@white_october_tcpdf.tcpdf'
      

Debugging Tips

  1. Error Handling: Wrap TCPDF calls in try-catch:

    try {
        $pdf->Output('file.pdf');
    } catch (TCPDFException $e) {
        // Log or handle error
        throw new \RuntimeException('PDF generation failed: '.$e->getMessage());
    }
    
  2. Logging: Enable TCPDF debug mode:

    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->setDebug(true); // Logs errors to stdout
    
  3. Output Modes:

    • 'I': Send inline (browser displays).
    • 'D': Force download.
    • 'S': Return as string (for APIs).
    • 'F': Save to file (specify path).
  4. Performance:

    • For dynamic content, pre-render HTML in Twig and pass to writeHTML().
    • Avoid regenerating the same PDF repeatedly (cache results).

Extension Points

  1. Custom TCPDF Class: Extend TCPDF to add reusable methods:
    class CustomTCPDF extends TCPDF {
        public function addTitle(string $title, int $size = 16) {
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware