Editing a existing pdf lead to creating a new pdf where old data is overwritten by the new file

StackOverflow https://stackoverflow.com/questions/21747266

  •  10-10-2022
  •  | 
  •  

Question

I am facing an issue while editing the existing pdf. Here I have a pdf where I just want to add a employee name on the first line of every page in pdf. But when I try to do this using fpdf and fpdi then it will save the new pdf with employee name and all the other data has been removed from the pdf. Here is the code which I am using for editing and saving a pdf.

<code>
<?php
define('FPDF_FONTPATH','font/');
require_once('fpdf.php');
require_once('fpdi.php');

$pdf = new FPDI();
// add a page
$pdf->AddPage();
// set the sourcefile
$pagecount = $pdf->setSourceFile('upload/linebreak.pdf');

// import page 1
$tplidx = $pdf->importPage(1);
for ($i = 1; $i < $pagecount; $i++) { 
              $tplidx = $pdf->ImportPage($i); 


                     $pdf->useTemplate($tplidx, 10, 10, 200);
                     $pdf->AddPage();

                     $pdf->SetFont('Arial');
                     $pdf->SetTextColor(0,0,0);
                     $pdf->SetFontSize(8);

                     if ($i>=1) {
                        //$pdf->SetXY(50, 124);
                        $pdf->Write(1, "Emp Name : Sanjay Singh");
                     }

                }

$pdf->Output("upload/new_linebreak_pdf.pdf", "F");
?>
<code>

My linebreak.pdf have data some thing like this (This is the employee rule for our organization..........This is the employee rule for our organization......This is the employee rule for our organization.....This is the employee rule for our organization....This is the employee rule for our organization)

On this I want to add a Employee Name on the first line but after editing it will generate new pdf like this(Emp Name : Sanjay Singh) Where other data which is already their will get deleted.

Thanks In Advance !

Was it helpful?

Solution

Your problem is that you're calling methods for FPDI in the wrong order. Here are the steps to take:

  1. Import the page you want to modify, get the template
  2. Add a new blank page to the document
  3. Load the template into that document
  4. Write additional content to that document

Here is a brief code example illustrating the above concept. I have tested this and gotten the output expected.

$pdf = new FPDI();
$pageCount = $pdf->setSourceFile('file.pdf');

//  Iterate through every page
for( $pageNo=1; $pageNo<=$pageCount; $pageNo++ )
{
    //  Import page
    $templateId = $pdf->importPage($pageNo);
    $pdf->getTemplateSize($templateId);
    $pdf->addPage('P');
    $pdf->useTemplate($templateId);

    //  Modify page
    $pdf->SetFont('Arial');
    $pdf->SetTextColor(0,0,0);
    $pdf->SetFontSize(8);
    $pdf->Text(50,124,"Emp Name : Sanjay Singh");
}

$pdf->Output("upload/new_linebreak_pdf.pdf", "F");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top