微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用PHP为现有PDF文件添加水印?

我需要使用PHP为现有的PDF文件添加水印.我在Google上搜索过它,但找不到合适的库.

我找到了创建PDF文件预览缩略图fpdf库,但我不知道它是否为现有PDF文件添加了水印.任何人都可以建议一个PHP库,而不是显示预览并为现有PDF文件添加水印?

解决方法:

只是一个使用FPDF和FPDI类的快速示例:

function PlaceWatermark($file, $text, $xxx, $yyy, $op, $outdir) {
    require_once('fpdf.PHP');
    require_once('fpdi.PHP');
    $name = uniqid();
    $font_size = 5;
    $ts=explode("\n",$text);
    $width=0;
    foreach ($ts as $k=>$string) {
        $width=max($width,strlen($string));
    }
    $width  = imagefontwidth($font_size)*$width;
    $height = imagefontheight($font_size)*count($ts);
    $el=imagefontheight($font_size);
    $em=imagefontwidth($font_size);
    $img = imagecreatetruecolor($width,$height);
    // Background color
    $bg = imagecolorallocate($img, 255, 255, 255);
    imagefilledrectangle($img, 0, 0,$width ,$height , $bg);
    // Font color
    $color = imagecolorallocate($img, 0, 0, 0);
    foreach ($ts as $k=>$string) {
        $len = strlen($string);
        $ypos = 0;
        for($i=0;$i<$len;$i++){
            $xpos = $i * $em;
            $ypos = $k * $el;
            imagechar($img, $font_size, $xpos, $ypos, $string, $color);
            $string = substr($string, 1);      
        }
    }
    imagecolortransparent($img, $bg);
    $blank = imagecreatetruecolor($width, $height);
    $tbg = imagecolorallocate($blank, 255, 255, 255);
    imagefilledrectangle($blank, 0, 0,$width ,$height , $tbg);
    imagecolortransparent($blank, $tbg);
    if ( ($op < 0) OR ($op >100) ){
        $op = 100;
    }
    imagecopymerge($blank, $img, 0, 0, 0, 0, $width, $height, $op);
    imagepng($blank,$name.".png");
    // Created Watermark Image
    $pdf = new FPDI();
    if (file_exists("./".$file)){
        $pagecount = $pdf->setSourceFile($file);
    } else {
        return FALSE;
    }
    $tpl = $pdf->importPage(1);
    $pdf->addPage();
    $pdf->useTemplate($tpl, 1, 1, 0, 0, TRUE);
    //Put the watermark
    $pdf->Image($name.'.png', $xxx, $yyy, 0, 0, 'png');
    if ($outdir === TRUE){
        return $pdf->Output();
    } else {
        return $pdf;
    }
}

PlaceWatermark("filename.pdf", "This is a lazy, but still simple test\n This should stand on a new line!", 30, 120, 100,TRUE);

用法:PlaceWatermark($filename,$text,$x,$y,$opacity,$directoutput);

$filename – 要在其中放置水印的PDF的路径
$text – 要添加的水印文本
$x – x坐标,用于放置水印
$y – y坐标要放置水印的位置
$opacity – 文本的不透明度
$directoutput – 如果TRUE函数输出PDF文件,否则它将返回$pdf
正如我已经说过的,这是一个非常快速和肮脏的例子,它需要一些改进.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐