Loading...

Writing to an existing PDF with FPDI

David Carr

2 min read - 10th Apr, 2020

FPDI allows existing PDF's to be used as a template for a new PDF. Whilst this does not give the ability to edit a PDF it can import one and add to it.

The FPDI extends FPDF so a copy of the latest version will be needed to use, place it in the same directory or update paths to it as needed.

It's recommended to use composer to install the library, you can do it like this:

In a composer.json file add the dependencies:

{
    "require": {
        "setasign/fpdf": "1.8.*",
        "setasign/fpdi": "^2.0"
    }
}

Then do a composer install in a terminal this will generate a vendor folder where the libraries are installed into.

Here's an example with comments.

<?php
require_once('vendor/autoload.php');

use setasign\Fpdi\Fpdi;

// initiate FPDI
$pdf = new Fpdi();

// add a page
$pdf->AddPage();

// set the source file
$pdf->setSourceFile("demo.pdf");

// import page 1
$tplId = $pdf->importPage(1);

// use the imported page and place it at point 10,10 with a width of 100 mm
$pdf->useTemplate($tplId);

// The new content
$fontSize = '15';
$fontColor = `255,0,0`;
$left = 16;
$top = 40;
$text = 'Sample Text over overlay';

//set the font, colour and text to the page.
$pdf->SetFont("helvetica", "B", 15);
$pdf->SetTextColor($fontColor);
$pdf->Text($left,$top,$text);

//see the results
$pdf->Output();

There are no built in options to get the page numbers so if you want to add them you need to know how many pages the PDF has then loop over them like this:

//optionally add additional pages, start the $i after the current page ie start from 2
for ($i=2; $i < 6; $i++) {
    $pdf->AddPage();
    $tplId = $pdf->importPage($i);
    $pdf->useTemplate($tplId);
}

 

0 comments
Add a comment