Writing to an existing PDF with PHP

David Carr

2 min read - 23rd Jan, 2014

This tutorial has been updated as of 10th April 2020, see the updated tutorial https://dcblog.dev/writing-to-an-existing-pdf-with-fpdi

 

On a recent project, I had the needed to modify an existing PDF, the modification would be done dynamically so I needed to use PHP for this, upon searching Google for 'php edit pdf' I came across a very useful script called FPDI

It's described as "Import pages from existing PDF documents and use them as templates in FPDF" Whilst this does not give the ability to edit a PDF it can import one and add to it.

The basic demo will only let you import the first page of the PDF not really that useful, but thanks to a snippet I came across you can loop through the other pages and add them to the PDF.

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.

require_once('FPDI/fpdf/fpdf.php');
require_once('FPDI/fpdi.php');
require_once('FPDI/fpdf_tpl.php');

// Original file with multiple pages 
$fullPathToFile = "sample.pdf";

class PDF extends FPDI {

    var $_tplIdx;

    function Header() {

        global $fullPathToFile;

        if (is_null($this->_tplIdx)) {

            // THIS IS WHERE YOU GET THE NUMBER OF PAGES
            $this->numPages = $this->setSourceFile($fullPathToFile);
            $this->_tplIdx = $this->importPage(1);

        }
        $this->useTemplate($this->_tplIdx, 0, 0,200);

    }

    function Footer() {}

}

// initiate PDF
$pdf = new PDF();

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


// The new content
$pdf->SetFont("helvetica", "B", 25);
$pdf->SetTextColor(255, 0, 0);
$pdf->Text(40,120,"Sample Text over overlay");

// THIS PUTS THE REMAINDER OF THE PAGES IN
if($pdf->numPages>1) {
    for($i=2;$i<=$pdf->numPages;$i++) {
        //$pdf->endPage();
        $pdf->_tplIdx = $pdf->importPage($i);
        $pdf->AddPage();
    }
}

//show the PDF in page
//$pdf->Output();

// or Output the file as forced download
$pdf->Output("sampleUpdated.pdf", 'D');

Download library from http://www.setasign.com/products/fpdi/downloads

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.