phpword增加水印

2020-09-25
<?php
$phpWord = new \PhpOffice\PhpWord\PhpWord();
		
$section = $phpWord->addSection();
$header = $section->addHeader();
$header->addWatermark(ROOT_PATH.'/Uploads/template/123.png', array(
	'width'         => 160,
	'height'        => 160,
	'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
	'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT,
	'posVertical'    => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_BOTTOM,
	'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
	'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
));

/*
与上面addWatermark方法实现效果相同,
$header->addImage(ROOT_PATH.'/Uploads/template/123.png', array(
	'width'         => 160,
	'height'        => 160,
	'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
	'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT,
	'posVertical'    => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_BOTTOM,
	'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
	'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
));
方法的不同之处:
1、addWatermark只能在$section->addHeader()中使用,
2、addImage可以再$section->addFooter()和$section->addHeader()中使用
*/

#由于水印本身的样式marginTop,marginLeft没什么效果,使用定位的方式调整水印的位置,但是上面的代码只能放到页面右下角

水印定位水平方向:
\PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_LEFT  #左
\PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER #中间
\PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT #右

水印定位垂直方向:
\PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_TOP #上
\PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_CENTER #中间
\PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_BOTTOM #下
\PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_INSIDE #与上效果相同
\PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_OUTSIDE #与下效果相同

水印位置定位计算起始位置:
\PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE #从页面边缘开始算
\PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN #从页边距算起

\PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN的效果

\PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE的效果

<?php

#可以将图片定位到指定的位置(根据marginLeft和marginTop),此方法不适用于addWatermark
$header->addImage(ROOT_PATH.'/Uploads/template/123.png', array(
	'width'         => 160,
	'height'        => 160,
	'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
	'posHorizontal'    => 'absolute',
	'posVertical'    => 'absolute',
	'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
	'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
	'marginLeft'       => 400,
	'marginTop'        => 700,
));

图片位置效果

{/if}