How to edit an existing PDF using PHP

A couple of weeks back I was asked to edit an existing PDF file and make changes to the content and save it back as a new PDF file.

Now nearly every one knows how to create a new PDF file using PHP either by generating HTML and then converting to PDF or writing PDF from scratch using any open source library but I believe editing an existing PDF is another thing altogether.

I Googled a bit and came across some posts on Stackoverflow and I was surprised that there were a a couple of libraries which served the purpose but the one which stood apart was SetAPDF.

They provide a free library to import and edit PDF documents.

As mentioned on their website

FPDI is a collection of PHP classes facilitating developers to read pages from existing PDF documents and use them as templates in FPDF, which was developed by Olivier Plathey. Apart from a copy of FPDF, FPDI does not require any special PHP extensions.

So now we can start writing a simple PHP script which will open an existing PDF file and then add a text to it and save it as a new PDF file.

I Googled and downloaded a sample PDF file

Next I downloaded the FPDI and FPDF packages which you can download from here and here respectively.

Finally I write the PHP script which will make the changes required

<?php
use setasign\Fpdi\Fpdi;

require_once('fpdf181/fpdf.php');
require_once('fpdi2/src/autoload.php');

$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile('sample.pdf');
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->SetFont('Arial', 'B', '24');
$pdf->SetXY(50,100);
$pdf->Write(10,'www.ApnaCode.com','https://www.apnacode.com');
$pdf->Output('sample_updated.pdf', 'F');

The above code will add the www.ApnaCode.com link at the location mentioned and save it as sample_updated.pdf

You can download the whole FPDI and FPDF PHP script as well

Hope the above helped!

Please follow and like us:
error

Be the first to comment

Leave a Reply

Your email address will not be published.