'How to write on existing pdf file in php

I know this question has been asked many times but I read all related answer and my problem is not solved yet. I can add text and image on a new blank pdf file by code below.

<?Php
require('fpdf.php');
$pdf = new FPDF('P','mm','A4');
$pdf->AddPage();

/* $pdf->setSourceFile("test1.pdf"); */

$pdf->SetFont('Helvetica');
$pdf->SetTextColor(255, 0, 0);
$pdf->SetXY(0, 5);
$pdf->Write(0, 'This is just a simple text');

$pdf->Image('sample.png',100,0);
$pdf->Output('file.pdf','F');
?>

But when I uncomment the line /* $pdf->setSourceFile("sourse.pdf"); */ to add text and image on existing pdf, I get Uncaught Error: Call to undefined method FPDF::setSourceFile() . Also when add

require('fpdi.php');
$pdf = new FPDI('P','mm','A4');

I get Uncaught Error: Class "setasign\Fpdi\FpdfTpl" not found . How can I solve this?



Solution 1:[1]

You have to set source file and after that import page from source file to your new created file by this way you can edit it. Please find more details from https://www.webniraj.com/2016/09/12/creating-editing-a-pdf-using-php/

// Create new Landscape PDF
$pdf = new FPDI('l');

// Reference the PDF you want to use (use relative path)
$pagecount = $pdf->setSourceFile( 'certificate.pdf' );

// Import the first page from the PDF and add to dynamic PDF
$tpl = $pdf->importPage(1);
$pdf->AddPage();

// Use the imported page as the template
$pdf->useTemplate($tpl);

// render PDF to browser
$pdf->Output();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheBlackBenzKid