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

Fpdi Laravel Package

setasign/fpdi

FPDI is a PHP library that imports pages from existing PDF files and uses them as templates in FPDF, TCPDF, or tFPDF. No special PHP extensions required. Supports modern, namespaced (v2) code with PSR-4 autoloading and better performance.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require setasign/fpdf:1.8.* setasign/fpdi:^2.5
    

    (or tecnickcom/tcpdf:6.6.*/setasign/tfpdf:1.33.* for TCPDF/tFPDF).

  2. Basic Usage:

    use setasign\Fpdi\Fpdi;
    $pdf = new Fpdi();
    $pdf->AddPage();
    $pdf->setSourceFile('template.pdf');
    $tplId = $pdf->importPage(1); // Import first page
    $pdf->useTemplate($tplId, 10, 10, 100); // Place template at (10,10) with width 100mm
    $pdf->Output('output.pdf');
    
  3. Key Classes:

    • setasign\Fpdi\Fpdi (FPDF)
    • setasign\Fpdi\Tcpdf\Fpdi (TCPDF)
    • setasign\Fpdi\Tfpdf\Fpdi (tFPDF)

First Use Case

Dynamic Invoice Generation:

  • Import a pre-designed invoice template (PDF).
  • Overlay dynamic data (e.g., client name, amounts) using FPDF’s text/drawing methods.
  • Output merged PDF with static template + dynamic content.

Implementation Patterns

Core Workflows

  1. Template Import & Placement:

    // Import all pages (optional: filter by page numbers)
    $pages = $pdf->setSourceFile('template.pdf');
    foreach ($pages as $i => $page) {
        $tplId = $pdf->importPage($i + 1); // +1 for 1-based indexing
        $pdf->useTemplate($tplId, 10, 10); // Default: full page size
    }
    
  2. Data Injection:

    // After useTemplate(), add dynamic content
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->SetXY(50, 50);
    $pdf->Cell(0, 10, 'Client: ' . $clientName);
    
  3. Multi-Page Handling:

    // Clone templates across pages
    $pdf->AddPage();
    $pdf->useTemplate($tplId, 0, 0, 0, 0, true); // true = clone
    

Integration Tips

  • FPDF/TCPDF/tFPDF Compatibility: Use the correct namespace/class (e.g., setasign\Fpdi\Tcpdf\Fpdi for TCPDF). TCPDF-specific features (e.g., writeHTML()) can be used after useTemplate().

  • Streaming Templates:

    $pdf->setSourceFileFromString(file_get_contents('template.pdf'));
    // or from a remote URL (with stream context)
    
  • Layered Templates: Use beginTemplate()/endTemplate() to group template operations:

    $pdf->beginTemplate();
    $pdf->useTemplate($tplId, 10, 10);
    $pdf->endTemplate();
    
  • Annotations/Links: Preserve hyperlinks from source PDF:

    $pdf->setSourceFile('template.pdf');
    $pdf->importPage(1);
    // Links are automatically imported; no extra config needed.
    

Laravel-Specific Patterns

  1. Service Provider Setup:

    // config/fpdi.php
    return [
        'default_template' => storage_path('app/templates/invoice.pdf'),
    ];
    
    // app/Providers/FpdiServiceProvider.php
    public function register() {
        $this->app->singleton(Fpdi::class, function ($app) {
            $pdf = new Fpdi();
            $pdf->setSourceFile(config('fpdi.default_template'));
            return $pdf;
        });
    }
    
  2. Dynamic Template Resolution:

    // In a controller
    $pdf = app(Fpdi::class);
    $pdf->setSourceFile(storage_path("app/templates/{$templateName}.pdf"));
    
  3. Queueable PDF Jobs:

    use Illuminate\Bus\Queueable;
    class GeneratePdfJob implements ShouldQueue {
        use Queueable;
        public $templatePath;
        public $data;
    
        public function handle() {
            $pdf = new Fpdi();
            $pdf->setSourceFile($this->templatePath);
            // Inject $this->data into template...
            $pdf->Output();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Page Unit Mismatch:

    • FPDI assumes source PDF uses points (pt). If the template uses millimeters (mm), scale coordinates:
      $pdf->useTemplate($tplId, 10 * 2.83464567, 10 * 2.83464567); // 1mm = 2.83464567pt
      
  2. Template Overwrite:

    • useTemplate() with 0 for width/height throws InvalidArgumentException. Use explicit values:
      $pdf->useTemplate($tplId, 10, 10, 190, 279); // A4 in mm
      
  3. Memory Leaks:

    • Always call $pdf->cleanUp() after use to release file handles:
      $pdf->Output();
      $pdf->cleanUp();
      
  4. TCPDF-Specific Issues:

    • TCPDF’s writeHTML() may not render correctly over templates. Use FPDF methods instead.
  5. Corrupted PDFs:

    • FPDI skips malformed objects but may fail on severely corrupted files. Validate templates first.

Debugging Tips

  1. Visual Debugging:

    • Use setDebug(true) to log parsing issues:
      $pdf->setDebug(true);
      
  2. Template Dimensions:

    • Verify page size with getTemplateSize():
      $size = $pdf->getTemplateSize($tplId);
      // $size = ['width' => 595, 'height' => 842] (A4 in pt)
      
  3. Common Errors:

    • "Invalid page number": Ensure page numbers are 1-based.
    • "Template not found": Check setSourceFile() path (use absolute paths in Laravel).
    • "Stream errors": Use file_get_contents() for local files or fopen() with streams.

Extension Points

  1. Custom Filters: Override setasign\Fpdi\PdfParser to handle proprietary PDF filters:

    class CustomParser extends \setasign\Fpdi\PdfParser {
        protected function createFilter($name) {
            if ($name === 'customFilter') {
                return new CustomFilter();
            }
            return parent::createFilter($name);
        }
    }
    
  2. Annotation Handling: Extend setasign\Fpdi\PdfReader\Annotation to modify links:

    $pdf->setAnnotationHandler(function ($annotation) {
        if ($annotation->getType() === 'Link') {
            $annotation->setUri('https://custom.url');
        }
        return $annotation;
    });
    
  3. Laravel Events: Trigger events before/after template processing:

    // In FpdiServiceProvider
    $pdf->setEventDispatcher(new \Illuminate\Events\Dispatcher());
    event(new \App\Events\PdfTemplateLoaded($pdf));
    
  4. Caching Templates: Cache imported pages to avoid reprocessing:

    $cacheKey = 'template_' . md5($templatePath);
    if (cache()->has($cacheKey)) {
        $tplId = cache()->get($cacheKey);
    } else {
        $tplId = $pdf->importPage(1);
        cache()->put($cacheKey, $tplId, now()->addHours(1));
    }
    

Laravel-Specific Quirks

  1. Storage Paths: Use storage_path() for template files to avoid hardcoding:

    $pdf->setSourceFile(storage_path('app/templates/invoice.pdf'));
    
  2. Blade Integration: Dynamically generate template paths in Blade:

    @php
    $pdf = new \setasign\Fpdi\Fpdi();
    $pdf->setSourceFile(storage_path("app/templates/{$template}.pdf"));
    @endphp
    
  3. Artisan Commands: Process templates via CLI:

    // app/Console/Commands/GeneratePdf.php
    public function handle() {
        $pdf = new Fpdi();
        $pdf->setSourceFile(storage_path('app/templates/report.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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport