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

Pdflib Laravel Package

evosys21/pdflib

PHP addons for FPDF/TCPDF/tFPDF to build advanced tag-formatted multicells and tables. Supports alignment/justification, mixed fonts/styles/colors, padding, frames/backgrounds, links, tabs, and sub/superscripts for rich PDF layouts.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require evosys21/pdflib
    

    Choose your PDF engine (FPDF, TCPDF, or tFPDF) by extending the appropriate base class:

    use EvoSys21\PdfLib\Tcpdf\Pdf; // Example for TCPDF
    class MyPdf extends Pdf { ... }
    
  2. First Use Case: Generate a simple table with formatted text:

    $pdf = new MyPdf();
    $pdf->AddPage();
    $pdf->AdvancedTable([
        ['data' => ['Header 1', 'Header 2'], 'header' => true],
        ['data' => ['<u>Bold</u> Text', 'Normal Text']],
    ]);
    $pdf->Output('output.pdf');
    
  3. Key Files to Explore:

    • docs/multicell.md: For advanced text formatting (tags, alignment, colors).
    • docs/table.md: For table-specific features (headers, row spans, page breaks).
    • examples/Tcpdf/: Practical examples (e.g., example-table-1-overview.php).

Implementation Patterns

Core Workflows

  1. Text Formatting with Tags: Use tag-based strings for dynamic styling (e.g., underlines, colors):

    $text = '<u>Underlined</u> and <c=red><b>Colored Bold</b></c> text';
    $pdf->AdvancedMulticell($text, 80, 10, '', 'L', false, 0, 0, false, 0, false);
    
    • Tags Supported:
      • <u>: Underline
      • <b>: Bold
      • <i>: Italic
      • <c=#RRGGBB>: Color
      • <s=size>: Font size
  2. Table Generation: Define tables as associative arrays with header and data keys:

    $pdf->AdvancedTable([
        ['data' => ['ID', 'Name'], 'header' => true, 'align' => ['C', 'L']],
        ['data' => [1, 'John Doe'], 'align' => ['L', 'L']],
    ]);
    
    • Key Features:
      • Auto-header repetition on page breaks.
      • Cell alignment (L, C, R, J).
      • Row/column spans (e.g., ['colspan' => 2]).
  3. Page Management: Disable page breaks for critical content:

    $pdf->AdvancedMulticell($text, 80, 10, '', 'L', false, 0, 0, false, 0, true, 50); // Disable break, min height 50
    
  4. Integration with Laravel: Use Service Providers to bind the PDF class:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind('pdf', function () {
            return new \App\Pdf\CustomPdf();
        });
    }
    

    Inject into controllers:

    public function generatePdf() {
        $pdf = app('pdf');
        $pdf->AddPage();
        // ... generate content
        return $pdf->stream('document.pdf');
    }
    

Pro Tips

  • Reuse PDF Classes: Extend EvoSys21\PdfLib\Tcpdf\Pdf once and reuse across projects.
  • Tag Shortcuts: Combine tags for complex styles:
    '<u><c=blue><b>Critical</b></c> Note</u>'
    
  • Debugging: Use setDebug(true) to log PDF generation steps (check docs/ for advanced usage).

Gotchas and Tips

Pitfalls

  1. Tag Parsing Quirks:

    • Unclosed Tags: <u>Text (missing </u>) may crash. Use htmlspecialchars() for dynamic content:
      $safeText = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
      
    • Nested Tags: Avoid overlapping tags (e.g., <u><b>Text</u></b>). Use <u><b>Text</b></u> instead.
  2. Table Layout Issues:

    • Page Breaks: Tables split automatically, but headers repeat. Override with:
      $pdf->AdvancedTable([...], false); // Disable header repetition
      
    • Column Widths: Use colWidths to enforce proportions:
      $pdf->AdvancedTable([...], null, null, ['colWidths' => [50, 100]]);
      
  3. Performance:

    • Large Tables: For >1000 rows, pre-calculate heights to avoid recalculations:
      $pdf->setAutoPageBreak(false);
      // Manually handle page breaks
      
  4. Font Conflicts:

    • Ensure fonts (e.g., Arial) are available in TCPDF's font directory (tcpdf/font/). Add custom fonts via:
      $pdf->AddFont('custom', '', 'customfont.php');
      

Debugging Tips

  • Log Errors: Enable TCPDF’s error logging:
    $pdf->setErrorLogging(true);
    
  • Inspect Output: Use Output('output.pdf', 'I') to download and manually check the PDF.
  • Check Tag Syntax: Validate tags with a regex:
    if (preg_match('/<[^>]+>/', $text)) {
        // Log or sanitize
    }
    

Extension Points

  1. Custom Tags: Extend the parser by overriding parseTags() in your PDF class:

    protected function parseTags($text) {
        // Add custom logic (e.g., <strike> for strikethrough)
        return parent::parseTags($text);
    }
    
  2. Hooks for Tables: Use onTableStart/onTableEnd callbacks:

    $pdf->setTableCallback(function ($pdf, $tableData) {
        // Pre-process table data (e.g., add IDs)
    });
    
  3. Laravel Blade Integration: Create a Blade directive for PDF generation:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('pdf', function ($expression) {
        return "<?php echo app('pdf')->{$expression}; ?>";
    });
    

    Usage:

    @pdf->AdvancedTable([...])
    

Configuration Quirks

  • TCPDF vs. FPDF:
    • TCPDF supports Unicode natively; FPDF requires manual encoding.
    • TCPDF’s AddPage() defaults to A4. Override with:
      $pdf->AddPage('L', 'Letter'); // US Letter size
      
  • Image Handling:
    • Use AdvancedTable with images key:
      ['data' => ['<img=logo.png>'], 'images' => ['logo.png']]
      
    • Ensure images are in public/ or provide full paths.

Laravel-Specific Tips

  • Storage: Save generated PDFs to storage/app/public/ and link via:
    return response()->file(storage_path('app/public/document.pdf'));
    
  • Queues: Offload PDF generation to queues:
    GeneratePdfJob::dispatch($data)->onQueue('pdfs');
    
    // Job class
    public function handle() {
        $pdf = new MyPdf();
        $pdf->generate($this->data)->save(storage_path('app/public/output.pdf'));
    }
    
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
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
spatie/mailcoach-vapor