Using fpdf to modify existing pdf in php

I have a bank of pdf files on my server, which when loading requires adding text to each page. I use fpdf to try to open the file, add text to each page, close the file and go to the browser.

$pdf = new FPDI(); $pdf->setSourceFile($filename); // import page 1 $tplIdx = $pdf->importPage(1); //use the imported page and place it at point 0,0; calculate width and height //automaticallay and ajust the page size to the size of the imported page $pdf->useTemplate($tplIdx, 0, 0, 0, 0, true); // now write some text above the imported page $pdf->SetFont('Arial', '', '13'); $pdf->SetTextColor(0,0,0); //set position in pdf document $pdf->SetXY(20, 20); //first parameter defines the line height $pdf->Write(0, 'gift code'); //force the browser to download the output $pdf->Output('gift_coupon_generated.pdf', 'D'); header("location: ".$filename); 

At that moment, it just tries to put some text anywhere in the pdf and save it, but I get an error

 FPDF error: You have to add a page first! 

If I can do this, I need it to add text to each page of the document, and not just 1, I donโ€™t know how to do this by reading the documentation

+6
source share
3 answers

Try to execute

 require_once('fpdf.php'); require_once('fpdi.php'); $pdf =& new FPDI(); $pdf->AddPage(); 

Use this page as a template, then

 $pdf->setSourceFile($filename); // import page 1 $tplIdx = $pdf->importPage(1); //use the imported page and place it at point 0,0; calculate width and height //automaticallay and ajust the page size to the size of the imported page $pdf->useTemplate($tplIdx, 0, 0, 0, 0, true); 

Let me know if you have errors.

+9
source

Since you need all the pages with text, one way to do this is to put the code in a loop.

Like this:

 // Get total of the pages $pages_count = $pdf->setSourceFile('your_file.pdf'); for($i = 1; $i <= $pages_count; $i++) { $pdf->AddPage(); $tplIdx = $pdf->importPage($i); $pdf->useTemplate($tplIdx, 0, 0); $pdf->SetFont('Arial'); $pdf->SetTextColor(255,0,0); $pdf->SetXY(25, 25); $pdf->Write(0, "This is just a simple text"); } 
+5
source

You can use the Dhek graphics tool to create a template in JSON format by defining the areas (borders, name, ...) that you want to add later to an existing PDF (using FPDF and dynamic data). See the document at https://github.com/cchantep/dhek/blob/master/README.md#php-integration .

+1
source

Source: https://habr.com/ru/post/925832/


All Articles