Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a watermark to an existing PDF file using PHP?

Tags:

php

I am in need of adding a watermark to an existing PDF file using PHP. I have searched on Google for it, but couldn't find any suitable library.

I found the fpdf library that creates preview thumbnails of PDF files, but I don't know if it adds watermarks to existing PDF files or not. Can anyone suggest a PHP library than can show preview and add watermarks to existing PDF files?

like image 402
Yasir Avatar asked May 26 '10 14:05

Yasir


1 Answers

Here is a MPDF practice, adding watermarks to every page of a landscape oriented PDF.

    //First, get the correct document size.
    $mpdf = new \Mpdf\Mpdf([
        'tempDir' => storage_path('app'),
        'orientation' => 'L'
    ]);

    $pagecount = $mpdf->SetSourceFile('[path]');

    $tplId = $mpdf->ImportPage(1);
    $size = $mpdf->getTemplateSize($tplId);

    //Open a new instance with specified width and height, read the file again
    $mpdf = new \Mpdf\Mpdf([
        'tempDir' => storage_path('app'),
        'format' => [$size['width'], $size['height']]
    ]);
    $mpdf->SetSourceFile('[path]');

    //Write into the instance and output it
    for ($i=1; $i <= $pagecount; $i++) { 
        $tplId = $mpdf->ImportPage($i);
        $mpdf->addPage();
        $mpdf->UseTemplate($tplId);
        $mpdf->SetWatermarkText('[Watermark Text]');
        $mpdf->showWatermarkText = true;
    }

    return $mpdf->output();
  • It took me a while to make the output result in correct size, and finally found the key is that you need to specify the width and height to the instance you are going to write. In my case, the input PDF files may have different sizes, so I have to initiate another instance for getting size before working on the writing one.

  • If your PDF version is newer than 1.4, PDFI will not work with it. You have to convert it to 1.4. I use xthiago/pdf-version-converter in my Laravel work.

like image 137
Mou Hsiao Avatar answered Sep 28 '22 11:09

Mou Hsiao