tecnickcom / TCPDF

Official clone of PHP library to generate PDF documents and barcodes
https://tcpdf.org
Other
4.18k stars 1.51k forks source link

How to add a watermark? #607

Open singi2016cn opened 1 year ago

singi2016cn commented 1 year ago

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

williamdes commented 1 year ago

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 :)