Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Writing to an existing PDF with FPDI

David Carr

Tutorials PHP & MySQL

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);
}

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.