You can apply a watermark on a PDF file using the package “setasign/fpdi-fpdf” in Laravel. Here are the steps:

Install the package:

composer require setasign/fpdi-fpdf

Create a new class for watermarking:

use FPDI;

class WatermarkPdf extends FPDI {
    public function Header() {}
    public function Footer() {}
    public function Watermark($file, $text) {
        // Set alpha to semi-transparency
        $this->SetAlpha(0.5);
        // Get the page width/height
        $ws = $this->getPageWidth();
        $hs = $this->getPageHeight();
        // Print the watermark
        if ($file) {
            $this->Image($file, 0, 0, $ws, $hs);
        }
        if ($text) {
            $this->SetFont('Arial', 'B', 50);
            $this->Rotate(45, $ws/2, $hs/2);
            $this->Text($ws/2, $hs/2, $text);
        }
        // Reset the transparency
        $this->SetAlpha(1);
    }
}

Use the class to watermark the PDF:

use WatermarkPdf;

$pdf = new WatermarkPdf();
$pdf->AddPage();
$pdf->setSourceFile('existing.pdf');
$pdf->Watermark('watermark.png', 'WATERMARK');
$pdf->Output('watermarked.pdf', 'F');

Note: You can use either an image file or a text as a watermark.

Leave a Reply

Your email address will not be published. Required fields are marked *

Upgrade PHP Version without using cPanel setting