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"
}
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');
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://fullstack-tutorials.com', 0, 2, 'C');