0

I'm trying to apply a watermark to an existing pdf using FPDI library, which is included in my project using composer package "setasign\fpdi-fpdf". Everytime I run the script I get "Template not Found" Exception. Here is the code:

    $pdf       = new \setasign\Fpdi\Fpdi();
    $pdf1      = new \setasign\Fpdi\Fpdi();
    $pageCount = $pdf1->setSourceFile($this->getCurrentFile());
    $tpl1      = $pdf1->importPage(1);

    $pdf2 = new \setasign\Fpdi\Fpdi();
    $pdf2->setSourceFile($watermarkPDF);
    $tpl2 = $pdf2->importPage(1);


    for($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
        $tpl1 = $pdf1->importPage($pageNo);

        $size = $pdf1->getTemplateSize($tpl1);
        $pdf->setSourceFile($this->getCurrentFile());
        if ($size['w'] > $size['h']) {
            $pdf->AddPage('L', array($size['w'], $size['h']));
        } else {
            $pdf->AddPage('P', array($size['w'], $size['h']));
        }

        $pdf->useTemplate($tpl1, 0, 0, 0);
        $pdf->useTemplate($tpl2, 0, 0, 0);
    }

The line that gives me this error is "$pdf->useTemplate($tpl1, 0, 0, 0);". How can I solve this error?

user3101803
  • 35
  • 1
  • 7

1 Answers1

0

You need to use only a single FPDI instance. Currently you are using 2 instances and try to use an imported page of instance A in instance B.

Your code should look like that:

$pdf = new \setasign\Fpdi\Fpdi();
$pdf->setSourceFile($watermarkPDF);
$watermarkTpl = $pdf->importPage(1);

$pageCount = $pdf->setSourceFile($this->getCurrentFile());

for($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
    $tpl = $pdf->importPage($pageNo);

    $size = $pdf->getTemplateSize($tpl);
    $this->AddPage($size['orientation'], $size);

    $pdf->useTemplate($tpl);
    $pdf->useTemplate($watermarkTpl);
}

$pdf->Output();
Jan Slabon
  • 4,736
  • 2
  • 14
  • 29