Yii 结合MPDF 给PDF文件添加多行水印

首先确保安装了mpdf扩展 composer require mpdf/mpdf

php 复制代码
public function createWaterPdf($file_path,$water_text)
    {
        date_default_timezone_set('PRC');
        ini_set('memory_limit', '6400M');
        ini_set('max_execution_time', '0');

        try{

            $mpdf = new Mpdf();
            $pageCount   = $mpdf->SetSourceFile($file_path); //读取原始文件页数
            $tplId       = $mpdf->ImportPage(1); //获取第一张信息
            $size        = $mpdf->getTemplateSize($tplId);
            $orientation = $size['orientation'] ?? 'P';

            //创建缓存文件夹
            $cachePath = Yii::$app->basePath.'/runtime/pdfwater';
            if (!is_dir($cachePath)) {
                mkdir($cachePath, 0777, true);
            }
            //第一步:创建水印背景图片
            $width  = ceil($size['width'] / 25.4 * 300); //换算成300分辨率对应的尺寸大小
            $height = ceil($size['height'] / 25.4 * 300);
            $image  = imagecreate($width, $height);
            $bg     = imagecolorallocate($image, 255, 255, 255);
            imagefill($image, 0, 0, $bg);

            imagepng($image,$cachePath.'/background.png');
            imagedestroy($image);

            //第二步:创建水印图片
            $image  = $cachePath . '/background.png';
            $info   = getimagesize($image);
            $imgExt = image_type_to_extension($info[2], false);  //获取文件后缀

            $fun = "imagecreatefrom{$imgExt}";
            $imgInfo = $fun($image);

            $fontFile  = Yii::$app->params['fontPath'] . '/simhei.ttf'; //字体文件名,必须要,需要下载对应的字体文件,放到指定的目录
            $fontSize  = 70; //字体尺寸
            $fontColor = ImageColorAllocate($imgInfo,0,0,0); //字体颜色,这里是黑色
            $textAngle = 30; //文字显示的角度,0表示水平显示

            $x_length = $info[0];
            $y_length = $info[1];

            $text_length = (mb_strlen($water_text) + 3)*0.833*70;
            //判断用多大的纸张
            if ($orientation == 'P') {
                $water_h = ceil($x_length/3)-100;
                $page_width = $size[0];
                $page_height = $size[1];
            } else {
                $water_h = ceil($y_length/3)-100;
                $page_width = $size[1];
                $page_height = $size[0];
            }
            if ($page_width > 900 || $page_width < 150 || $page_height > 1200 || $page_height < 150) return ['code'=>2,'msg'=>'文件尺寸不符合要求']; //此处不限制文件大小也行

            $water_w = $text_length * 1.732;
            if ($water_w < 1000) $water_w = 1000;
            //重复添加水印
            for ($x = 0; $x < $x_length; $x += $water_w) {
                for ($y = 0; $y < $y_length; $y += $water_h) {
                    imagefttext($imgInfo,$fontSize,$textAngle,$x,$y,$fontColor,realpath($fontFile),$water_text); //把文字覆盖到图片上
                }
            }

            $quality = 100;
            if($imgExt == 'png') $quality = 9;//输出质量,JPEG格式(0-100),PNG格式(0-9)
            $getImgInfo = "image{$imgExt}";
            $getImgInfo($imgInfo, $cachePath.'/watermark.png', $quality);

            imagedestroy($imgInfo);

            //第三步:开始添加水印操作
            $arrPage = [
                'sheet-size' => [$page_width,$page_height], //指定纸张大小
                'orientation' => $orientation, //指定纸张方向
            ];

            for($i=1; $i<=$pageCount; $i++){ //循环添加原始文件
                $mpdf->AddPageByArray($arrPage);
                $tplId = $mpdf->ImportPage($i);
                $mpdf->UseTemplate($tplId);

                //开始给pdf添加水印
                $mpdf->SetWatermarkImage($cachePath.'/watermark.png');
                $mpdf->showWatermarkImage = true;
            }

            $mpdf->Output($cachePath.'/watermask.pdf','F'); //新文件

           
        }catch (\Exception $e){
            return ['code'=>1,'msg'=>$e->getMessage()];
        }

    }
相关推荐
2401_890665863 小时前
免费送源码:Java+ssm+HTML 三分糖——甜品店网站设计与实现 计算机毕业设计原创定制
java·python·微信小程序·html·php·课程设计·android-studio
大G哥15 小时前
PHP标签+注释+html混写+变量
android·开发语言·前端·html·php
傻啦嘿哟15 小时前
HTTP代理基础:网络新手的入门指南
开发语言·php
陌殇殇19 小时前
Java使用IText7动态生成带审批文本框的PDF文档
java·pdf
BXCQ_xuan21 小时前
Typecho博客网站头部SEO优化完整指南
运维·服务器·数据库·php·web
人类群星闪耀时21 小时前
5G赋能远程医疗:从愿景到现实的技术变革
开发语言·5g·php
onejason1 天前
利用 PHP 爬虫按关键字搜索 1688 商品详情:实战指南
前端·php
foryoufeng1 天前
Laravel代码生成器,快速构建项目代码,统一团队编码风格
php·laravel
Ven%1 天前
VsCode如何使用默认程序打开word Excel pdf等文件
ide·vscode·pdf·编辑器
软件工程小施同学1 天前
计算机学报 2024年 区块链论文 录用汇总 附pdf下载
pdf·区块链