1、寻找合适的工具
- 试了几个插件,发现中文都容易乱码,文字水印都不支持平铺,为了更好地实现效果,只能做一张水印图片,使用图片水印的方式, 综合考虑 选取了 setasign/fpdf,setasign/fpdi 和 pdfcpu 去实现功能。
2、PHP实现添加水印实例
composer require setasign/fpdf
composer require setasign/fpdi
require_once(__DIR__ . "/../vendor/setasign/fpdf/Fpdf.php");
require_once(__DIR__ . "/../vendor/setasign/fpdi/src/autoload.php");
class PdfWater
{
function addImageWater($oldFile, $newFile, $waterFile)
{
$pdf = new Fpdi();
$pageCount = $pdf->setSourceFile($oldFile);//获取页数
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);//导入页面
$pdf->image($waterFile, 0, 0, $size['width'],$size['height']);//全屏背景图片水印
}
$pdf->Output('F', $newFile, false);//I输出output,D下载download,F保存file_put_contents,S返回return
}
}
function addTxtWater($oldFile, $newFile, $waterText)
{
$pdf = new Fpdi();
$pageCount = $pdf->setSourceFile($oldFile);
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);//使用导入的页面
$pdf->SetFont('Arial', 'B', '24');//设置字体
$family = ['courier', 'helvetica', 'times', 'symbol', 'zapfdingbats'];
$pdf->SetFont('helvetica', 'U', '50');
$pdf->SetXY($size['width'], $size['height']);
$pdf->Write(7, $waterText);//写入水印 - 中文会乱码 建议使用中文图片
}
$pdf->Output('F', $newFile, false); //I输出output,D下载download,F保存file_put_contents,S返回return
}
3、GO语言实现PDF添加水印
package main
import (
"github.com/pdfcpu/pdfcpu/pkg/api"
"github.com/pdfcpu/pdfcpu/pkg/pdfcpu"
)
func main() {
oldFile:="/Users/tal/Desktop/1.pdf"
newFile:="/Users/tal/Desktop/output.pdf"
waterFile:="/Users/tal/Desktop/eye.png"
water(oldFile,newFile,waterFile)
}
func water(oldFile string,newFile string,waterFile string) {
onTop := true
wm, _ := pdfcpu.ParseImageWatermarkDetails(waterFile, "sc:4 abs, d:1, op:.4, pos:c", onTop,1)
api.AddWatermarksFile(oldFile, newFile, nil, wm, nil)
}
/CLI pdfcpu watermark add -mode image '/Users/tal/Desktop/eye.png' 's:1 abs, rot:0' /Users/tal/Desktop/1.pdf /Users/tal/Desktop/output.pdf
源代码分享
- https://github.com/CiaraLi/pdf-demo.git
|