One of the recommended packages for working with PDFs in Laravel is the setasign/fpdi package, which is a free PDF document importer. It allows you to read existing PDF documents and to reuse them as templates in FPDI. To add headers and footers to all pages, you can use FPDI in combination with FPDF, which is a PHP class to generate PDFs.
Here's how you can use setasign/fpdi with Laravel:
- Install the package via Composer:
composer require setasign/fpdi
- Create a new class that extends the
FPDIclass, where you will customize the header and footer:
use setasign\Fpdi\Fpdi;
class PDF extends Fpdi {
public function Header() {
// Your code to add a header
$this->SetFont('Arial', 'B', 12);
$this->Cell(0, 10, 'Your Header Text', 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
public function Footer() {
// Your code to add a footer
$this->SetY(-15);
$this->SetFont('Arial', 'I', 8);
$this->Cell(0, 10, 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
- Use the
PDFclass to import the existing PDF and add headers and footers:
$pdf = new PDF();
$pageCount = $pdf->setSourceFile('path-to-your-uploaded-pdf.pdf');
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$pdf->AddPage();
$templateId = $pdf->importPage($pageNo);
$pdf->useTemplate($templateId);
// The Header and Footer methods are called automatically by AddPage()
}
$pdf->Output('F', 'path-to-save-the-modified-pdf.pdf');
Make sure to replace 'path-to-your-uploaded-pdf.pdf' with the actual path to the uploaded PDF file and 'path-to-save-the-modified-pdf.pdf' with the path where you want to save the modified PDF.
This is a basic example, and you might need to adjust the code to fit your specific requirements, such as the header/footer design, alignment, and so on. FPDI is quite powerful and can be used to manipulate PDFs in various ways, so it's a good choice for your requirement in a Laravel application.