Using fpdf to modify existing pdf in php

Using fpdf to modify existing pdf in php

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Using FPDI to Modify Existing PDFs in PHP

Appending text to an existing PDF requires understanding how the library handles page states. The error FPDF error: You have to add a page first! occurs because your code attempts to write content immediately after importing a template but before explicitly creating a writable page context for that imported data. In FPDI (FPDF + iText), importing a page ($pdf->importPage) only loads the visual representation into memory; it does not automatically switch the current page state to "ready for writing." You must ensure the document is in a state where new content can be added.

To fix the immediate error, you need to call $pdf->useTemplate($tplIdx, ...) which places the imported PDF onto the canvas. However, simply placing the template doesn't guarantee that subsequent Write or Cell commands will execute correctly if the internal page counter isn't aligned with your expectations. The robust pattern is to ensure the document is ready for output before attempting to draw.

Here is the corrected approach for appending text to a single page using FPDI:

$pdf = new FPDF('P', 'mm', 'A4'); // Create a new instance if starting fresh, or use existing
$pdf->AddPage(); // Crucial: This creates an empty page buffer

$pdf->setSourceFile($filename); 
$tplIdx = $pdf->importPage(1); 

// Use the imported template at position 0,0. 
// The third parameter (width) and fourth (height) should match the source page size 
// if you want to preserve dimensions exactly, or omit them to let FPDI calculate.
$pdf->useTemplate($tplIdx, 0, 0, $pdf->w - 2, $pdf->h - 2); 

// Now the page state is valid for writing.
$pdf->SetFont('Arial', '', '13'); 
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY(20, 20);
$pdf->Write(0, 'gift code');

$pdf->Output('gift_coupon_generated.pdf', 'D');

The critical step missing in the original snippet was ensuring a page existed in the buffer before importPage or useTemplate manipulated the state. By explicitly adding a page (or relying on FPDI's logic when using templates correctly), you avoid the "add a page first" crash.

Iterating Through Multiple Pages

If your requirement is to append text to every page in the document, the single-page approach above is insufficient. You must loop through the total number of pages defined in the source file. The FPDF class provides the $pdf->GetPageCount() method (via the imported PDF object) which returns the total page count.

You can iterate like this:

$pdf = new FPDI();
$pdf->setSourceFile($filename);
$pages = $pdf->getPageCount();

for ($pageNo = 1; $pageNo <= $pages; $pageNo++) {
    // Import the specific page we want to modify
    $tplIdx = $pdf->importPage($pageNo);
    
    // Use the template. Note: FPDI handles the positioning automatically 
    // if you don't specify coordinates that conflict with existing content.
    $pdf->useTemplate($tplIdx, 0, 0, $pdf->w - 2, $pdf->h - 2);

    // Reset font and position for each page to ensure consistent placement
    $pdf->SetFont('Arial', '', '13'); 
    $pdf->SetTextColor(0, 0, 0);
    
    // Set coordinates relative to the top-left of the current page
    $pdf->SetXY(20, 20);
    
    // Write the text
    $pdf->Write(0, 'gift code');
}

$pdf->Output('gift_coupon_generated.pdf', 'D');

Important Considerations and Trade-offs

  1. Coordinate Systems: When using useTemplate, be mindful of margins. If your source PDF has a large header or footer, placing new text at (20, 20) might overlap existing content. You may need to adjust the Y-coordinate dynamically based on the page index if you want to skip headers (e.g., $y = 50 + ($pageNo * 15)).
  2. Page Size Variations: Most bank PDFs are uniform, but some documents mix A4 and Letter sizes or include landscape pages. Always check $pdf->getPageDimension($pageNo) inside the loop if you suspect mixed orientations. Forcing a single page size on all imports can cause clipping errors.
  3. Font Embedding: The SetFont call above assumes standard PDF fonts are available. If your source PDF uses custom embedded fonts, simply calling SetFont('Arial') might result in substitution or blank text if the character set doesn't match. For production reliability, consider using $pdf->useTemplate($tplIdx, 0, 0, 0, 0, true) with the last parameter set to true to preserve the exact rendering context of the original page, including font mappings.
  4. Performance: Processing large PDFs (100+ pages) in PHP using FPDI is resource-intensive because it imports the entire page vector data into memory for every iteration. For massive files, consider processing in batches or switching to a server-side rendering solution if latency becomes an issue.

By explicitly managing the page loop and verifying page dimensions, you can reliably append metadata or watermarks to any multi-page document without encountering state errors.

Our network