PHP使用FPDF、Fpdi类库给PDF文件添加水印

/**
 * PDF文件加水印
 * composer命令安装:composer require setasign/fpdf
 * composer命令安装:composer require setasign/fpdi
 */
public function add_water($type = 1){
    $pdf = new Fpdi();
    $file = 'Upload/all_to_path/report_file/FA065307C8FF0236FC2002DAA098D439.pdf';
    //获取页数
    $pageCount = $pdf->setSourceFile($file);
    //遍历所有页面
    for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++){
        //导入页面
        $templateId = $pdf->importPage($pageNo);
        //获取导入页面的大小
        $size = $pdf->getTemplateSize($templateId);
        //创建页面(横向或纵向取决于导入的页面大小)
        if ($size['width'] > $size['height']){
            $pdf->AddPage('L', array($size['width'], $size['height']));
        }else {
            $pdf->AddPage('P', array($size['width'], $size['height']));
        }
        //使用导入的页面
        $pdf->useTemplate($templateId);

        if($type == 1){//文字水印
            //设置字体
            //$pdf->SetFont('Arial','B','24');
            $family = ['courier', 'helvetica', 'times', 'symbol', 'zapfdingbats'];
            $pdf->SetFont('helvetica','U','50');
            //设置位置 - 加在中间位置
            $center_x = $size['width']/2;
            $center_y = $size['height']/2;
            $pdf->SetXY($center_x, $center_y);
            //写入水印 - 中文会乱码 建议使用中文图片
            $pdf->Write(7, 'ROOT_ICO');
        }else{//图片水印
            $center_x = $size['width']/2 - 40;$center_y = $size['height']/2;
            $pdf->image("Upload/all_to_path/report_file/water_mark.png", $center_x, $center_y, 80);//中间水印
            $pdf->image("Upload/all_to_path/report_file/water_mark2.png", 0, 0,210);//全屏背景水印
        }
    }
    //I输出output,D下载download,F保存file_put_contents,S返回return
    $pdf->Output('F','Upload/all_to_path/report_file/save.pdf',false);
}

1.中间水印效果

2.全屏背景水印效果

发布了21 篇原创文章 · 获赞 6 · 访问量 1505

猜你喜欢

转载自blog.csdn.net/weixin_42047371/article/details/99632700
今日推荐