How to Add Watermark to Existing PDF using PHP

PDF (Portable Document Format) is widely a popular file format which we used for variour purpose in online work.

Generally, the PDF file is used to share text/image data for offline use. In the website we generate invoices, reports and other data for interenal use or to client against their used service on the website. In the web application, a PDF file is created with HTML content to make dynamic data available for download.

In this tutorial we will learn how we can easily create PDF documents dynamically and convert HTML content to PDF using PHP.

Some time we need to print specific header and footer in the PDF like company name, date, watermark etc. for example when we get bill from some big comapny in PDF format then most of the time they watermark their PDF with their company name or logo. Same we will learn in today’s tutorial. Today we will learn how we can add watermark to existing PDF usign PHP.

We can use Dompdf to create the PDF from HTML and add the watter in that file but what if we already have PDF generated on our website or somewhere in the system, then if we want to add the watermark or some particular text to that existing PDF, that we can not do with Dompdf . In this tutorial, we will learn how we can add a watermark to an existing PDF documents using PHP.

In this example script, we will use FPDF and FPDI libraries to add watermark images to PDF with PHP. You can add text or image as a watermark to an existing PDF documents using PHP.

Install FPDF and FPDI Library

Run the following command to install FPDF and FPDI library using composer. If you don’t know how to use composer, please visit https://getcomposer.org/

composer require setasign/fpdi-fpdf

Note that: You don’t need to download the FPDF-FPDI library separately, all the required files are included in the source code.

Include autoloader to load FPDI library and helper functions in the PHP file.

// Load Fpdi library 
use setasign\Fpdi\Fpdi; 
require_once('vendor/autoload.php');

Add Text Watermark to PDF

The following example code adds watermark text to the existing PDF file using PHP.

  • Specify source PDF file and watermark text.
  • Configure text font, weight, and height using PHP imagefontheight() and imagefontwidth() function.
  • Create blank image with imagecreatetruecolor() function.
  • Set background and font color with imagecolorallocate() function.
  • Create image with imagepng() function.
  • Initialize Fpdi class and set the source PDF file using setSourceFile() method.
  • Add watermark to PDF pages using importPage()getTemplateSize()addPage()useTemplate(), and Image() methods of Fpdi class.
  • Render the generated PDF using the Output() function of Fpdi class.
<?php 

// Load Fpdi library 
use setasign\Fpdi\Fpdi; 
require_once('vendor/autoload.php');

// Source file and watermark config 
$file = 'documents/test.pdf'; 
$text = 'atcodex.com'; 
 
// Text font settings 
$name = uniqid(); 
$font_size = 5; 
$opacity = 100; 
$ts = explode("\n", $text); 
$width = 0; 
foreach($ts as $k=>$string){ 
    $width = max($width, strlen($string)); 
} 
$width  = imagefontwidth($font_size)*$width; 
$height = imagefontheight($font_size)*count($ts); 
$el = imagefontheight($font_size); 
$em = imagefontwidth($font_size); 
$img = imagecreatetruecolor($width, $height); 
 
// Background color 
$bg = imagecolorallocate($img, 255, 255, 255); 
imagefilledrectangle($img, 0, 0, $width, $height, $bg); 
 
// Font color settings 
$color = imagecolorallocate($img, 0, 0, 0); 
foreach($ts as $k=>$string){ 
    $len = strlen($string); 
    $ypos = 0; 
    for($i=0;$i<$len;$i++){ 
        $xpos = $i * $em; 
        $ypos = $k * $el; 
        imagechar($img, $font_size, $xpos, $ypos, $string, $color); 
        $string = substr($string, 1);       
    } 
} 
imagecolortransparent($img, $bg); 
$blank = imagecreatetruecolor($width, $height); 
$tbg = imagecolorallocate($blank, 255, 255, 255); 
imagefilledrectangle($blank, 0, 0, $width, $height, $tbg); 
imagecolortransparent($blank, $tbg); 
$op = !empty($opacity)?$opacity:100; 
if ( ($op < 0) OR ($op >100) ){ 
    $op = 100; 
} 
 
// Create watermark image 
imagecopymerge($blank, $img, 0, 0, 0, 0, $width, $height, $op); 
imagepng($blank, $name.".png"); 
 
// Set source PDF file 
$pdf = new Fpdi(); 
if(file_exists("./".$file)){ 
    $pagecount = $pdf->setSourceFile($file); 
}else{ 
    die('Source PDF not found!'); 
} 
 
// Add watermark to PDF pages 
for($i=1;$i<=$pagecount;$i++){ 
    $tpl = $pdf->importPage($i); 
    $size = $pdf->getTemplateSize($tpl); 
    $pdf->addPage(); 
    $pdf->useTemplate($tpl, 1, 1, $size['width'], $size['height'], TRUE); 
     
    //Put the watermark 
    $xxx_final = ($size['width']-50); 
    $yyy_final = ($size['height']-25); 
    $pdf->Image($name.'.png', $xxx_final, $yyy_final, 0, 0, 'png'); 
} 
@unlink($name.'.png'); 
 
// Output PDF with watermark 
$pdf->Output();

Add Image Watermark to PDF

The following example code adds a watermark image to an existing PDF file using PHP.

  • Specify source PDF file and watermark image.
  • Initialize Fpdi class and set the source PDF file using setSourceFile() method.
  • Add watermark image to PDF pages using importPage()getTemplateSize()addPage()useTemplate(), and Image() methods of Fpdi class.
  • Render the generated PDF with watermark using the Output() function of Fpdi class.
<?php 

// Load Fpdi library 
use setasign\Fpdi\Fpdi; 
require_once('vendor/autoload.php');

// Source file and watermark config 
$file = 'documents/Proposal.pdf'; 
$text_image = 'images/logo.png'; 
 
// Set source PDF file 
$pdf = new Fpdi(); 
if(file_exists("./".$file)){ 
    $pagecount = $pdf->setSourceFile($file); 
}else{ 
    die('Source PDF not found!'); 
} 
 
// Add watermark image to PDF pages 
for($i=1;$i<=$pagecount;$i++){ 
    $tpl = $pdf->importPage($i); 
    $size = $pdf->getTemplateSize($tpl); 
    $pdf->addPage(); 
    $pdf->useTemplate($tpl, 1, 1, $size['width'], $size['height'], TRUE); 
     
    //Put the watermark 
    $xxx_final = ($size['width']-60); 
    $yyy_final = ($size['height']-25); 
    $pdf->Image($text_image, $xxx_final, $yyy_final, 0, 0, 'png'); 
} 
 
// Output PDF with watermark 
$pdf->Output();

Output PDF with Watermark

Output()  is a default method to output the final PDF in the browser. You can directly save and downloa dthe generated PDF by using some parameters in the Output() method.
First Parameter:

  • I – (default) Output PDF to browser.
  • D – Download PDF file.
  • F – Save PDF to the local file.

Second Parameter:
Specify the file name of the PDF to download.

// Output to browser 
$pdf->Output(); 
 
// Download PDF file 
$pdf->Output('D', 'my-document.pdf'); 
 
// Save PDF to local file 
$pdf->Output('F', 'my-document.pdf');

Hope this tutorial solved your problem. For more about, how to convert html to PDF using dompdf you can simply visit below link.

You can also check

Convert HTML to PDF in Laravel with Dompdf

How to Count The Number of Pages in a PDF file

How to generate PDF file using PHP and MPDF library

How to Convert PDF to JPEG Image using PHP