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.
Installation:
composer require setasign/fpdf:1.8.* setasign/fpdi:^2.5
(or tecnickcom/tcpdf:6.6.*/setasign/tfpdf:1.33.* for TCPDF/tFPDF).
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');
Key Classes:
setasign\Fpdi\Fpdi (FPDF)setasign\Fpdi\Tcpdf\Fpdi (TCPDF)setasign\Fpdi\Tfpdf\Fpdi (tFPDF)Dynamic Invoice Generation:
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
}
Data Injection:
// After useTemplate(), add dynamic content
$pdf->SetFont('Arial', 'B', 12);
$pdf->SetXY(50, 50);
$pdf->Cell(0, 10, 'Client: ' . $clientName);
Multi-Page Handling:
// Clone templates across pages
$pdf->AddPage();
$pdf->useTemplate($tplId, 0, 0, 0, 0, true); // true = clone
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.
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;
});
}
Dynamic Template Resolution:
// In a controller
$pdf = app(Fpdi::class);
$pdf->setSourceFile(storage_path("app/templates/{$templateName}.pdf"));
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();
}
}
Page Unit Mismatch:
$pdf->useTemplate($tplId, 10 * 2.83464567, 10 * 2.83464567); // 1mm = 2.83464567pt
Template Overwrite:
useTemplate() with 0 for width/height throws InvalidArgumentException. Use explicit values:
$pdf->useTemplate($tplId, 10, 10, 190, 279); // A4 in mm
Memory Leaks:
$pdf->cleanUp() after use to release file handles:
$pdf->Output();
$pdf->cleanUp();
TCPDF-Specific Issues:
writeHTML() may not render correctly over templates. Use FPDF methods instead.Corrupted PDFs:
Visual Debugging:
setDebug(true) to log parsing issues:
$pdf->setDebug(true);
Template Dimensions:
getTemplateSize():
$size = $pdf->getTemplateSize($tplId);
// $size = ['width' => 595, 'height' => 842] (A4 in pt)
Common Errors:
setSourceFile() path (use absolute paths in Laravel).file_get_contents() for local files or fopen() with streams.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);
}
}
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;
});
Laravel Events: Trigger events before/after template processing:
// In FpdiServiceProvider
$pdf->setEventDispatcher(new \Illuminate\Events\Dispatcher());
event(new \App\Events\PdfTemplateLoaded($pdf));
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));
}
Storage Paths:
Use storage_path() for template files to avoid hardcoding:
$pdf->setSourceFile(storage_path('app/templates/invoice.pdf'));
Blade Integration: Dynamically generate template paths in Blade:
@php
$pdf = new \setasign\Fpdi\Fpdi();
$pdf->setSourceFile(storage_path("app/templates/{$template}.pdf"));
@endphp
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'));
//
How can I help you explore Laravel packages today?