Select Page

PHP Write Text Into an Existing PDF

This tutorial will show you how to write text into an existing PDF by using PHP. We are using Setasign‘s great PDF libraries to do the job.

In your composer.json, add the following

    "repositories": [
        {
            "type": "composer",
            "url": "https://www.setasign.com/downloads/"
        }
    ],
    "require": {
        "setasign/fpdf": "^1.8",
        "setasign/fpdi": "^2.0",
        "setasign/fpdi_pdf-parser": "2.0.4"
    }
  • The setasign/fpdf is a free library that you can generate PDFs with PHP. You can also use TCPDF or tFPDF. They both work with the other libraries required here, as stated in Setasign’s installation manual.
  • The setasign/fpdi can import pages from existing PDF documents and uses them as templates in FPDF
  • The setasign/fpdi_pdf-parser is an optional addition but highly recommended. By default, FPDI can handle PDF documents up to PDF version 1.4. Beginning from PDF version 1.5, there were new compression features introduced which involves internal structure changes how a PDF document can be created. This plugin is not free, but worth buying.

Let’s have an A4-sized PDF and add a line of text in the middle of the document. In your PHP code:


$pdf = new Fpdi;

$pdf->AddPage();
$pdf->setSourceFile('./path-to-existing-A4-sized.pdf');

// We import only page 1
$tpl = $pdf->importPage(1);

// Let's use it as a template from top-left corner to full width and height
$pdf->useTemplate($tpl, 0, 0, null, null);

// Set font and color
$pdf->SetFont('Helvetica', 'B', 20); // Font Name, Font Style (eg. 'B' for Bold), Font Size
$pdf->SetTextColor(0, 0, 0); // RGB

// Position our "cursor" to left edge and in the middle in vertical position minus 1/2 of the font size
$pdf->SetXY(0, 139.7-10);

// Add text cell that has full page width and height of our font
$pdf->Cell(215.9, 20, 'This text goes to middle', 0, 2, 'C');

// Output our new pdf into a file
// F = Write local file
// I = Send to standard output (browser)
// D = Download file
// S = Return PDF as a string
$pdf->Output('/tmp/new-file.pdf', 'F');

Internal Links in PDF

Note! When you import the PDF as a template, all internal links will get lost, and only texts will remain. To add a link to the PDF, you can add it as text:

$pdf->Cell(215.9, 20, 'https://jannerantala.com', 0, 2, 'C');

Did you find this tutorial helpful? Please share:

Photo by Luca Bravo on Unsplash

Subscribe to newsletter

We will never send you any marketing material