TCPDF icon indicating copy to clipboard operation
TCPDF copied to clipboard

How to add a watermark?

Open singi2016cn opened this issue 1 year ago • 1 comments

How to add a watermark?

As shown below:

image

I've tried using the image method (public function Image())

However, if a complete picture cannot be placed vertically, a new blank page will be generated with a separate picture.

The main code is as follows

        $pdfPath = path('t.pdf');
        $waterMarkPath = path('watermark.png');
        $pdfSavePath = path('wm_' . pathinfo($pdfPath, PATHINFO_BASENAME));

        $pdf = new Fpdi();
        list($waterMarkTrueWidth, $waterMarkTrueHeight) = getimagesize($waterMarkPath);
        $pageCount = $pdf->setSourceFile($pdfPath);
        for ($i = 1; $i <= $pageCount; $i++) {
            $templateId = $pdf->importPage($i);
            $size = $pdf->getTemplateSize($templateId);

            if ($size['width'] > $size['height']) {
                $pdf->AddPage('L', [$size['width'], $size['height']]);
            } else {
                $pdf->AddPage('P', [$size['width'], $size['height']]);
            }
            $pdf->useImportedPage($templateId);

            $waterMarkWidth = bcdiv($size['width'], 4);
            $waterMarkHeight = bcdiv($waterMarkTrueHeight, bcdiv($waterMarkTrueWidth, $waterMarkWidth));
            for ($h=0;$h < $size['height'];$h += $waterMarkHeight) {
                for($w=0;$w < $size['width'];$w += $waterMarkWidth) {
                    $pdf->setXY($w, $h);
                    $pdf->Image($waterMarkPath, $w, $h, $waterMarkWidth);
                }
            }
        }

        $pdf->Output($pdfSavePath, 'F');

output file: wm_t.pdf

image image

singi2016cn avatar Apr 17 '23 07:04 singi2016cn

You should probably ask for help on websites like StackOverflow. This is not a support forum, I would have gladly helped but I am lacking time to investigate.

Please post here the StackOverflow/forum link and keep us posted too :)

williamdes avatar Jun 14 '23 08:06 williamdes