单文件
引入
import {
downloadWatermarkedPdf
} from "@/utils/fileOperation";
//下载方法里面调用即可
const name = this.multipleSelection[0].folder_name;
downloadWatermarkedPdf(fileUrl, name);
中文水印关键 ../../public/font/font.ttf
链接: https://pan.baidu.com/s/1gMTwT4PzfSWA2SnPUSY__A?pwd=rkd8 提取码: rkd8 复制这段内容后打开百度网盘手机App,操作更方便哦
fileOperation.js
import { degrees, PDFDocument, StandardFonts, rgb } from "pdf-lib";
import fontkit from "@pdf-lib/fontkit";
// 单个图片下载加水印
export async function addWatermarkToImage(imgUrl, text, name) {
var image = new Image();
image.setAttribute("crossOrigin", "anonymous");
image.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
// 设置水印样式
context.font = "20px HelveticaNeue-Medium";
context.fillStyle = "rgba(0.1, 0.1, 0.1,0.1)";
// 计算倾斜角度的正切值
var tan45 = Math.tan((45 * Math.PI) / 180);
var watermarkInterval = 20;
// 根据水印间隔计算垂直方向上的起始位置
var startY = watermarkInterval;
// 遍历每一行水印
while (startY < image.height) {
var startX = watermarkInterval;
// 遍历每一列水印
while (startX < image.width) {
// 绘制倾斜的水印
context.save();
context.translate(startX, startY);
context.rotate(-Math.PI / 4);
context.fillText(text, 0, 0);
context.restore();
// 计算下一个水印的起始位置
startX += context.measureText(text).width + watermarkInterval;
}
// 计算下一行水印的起始位置
startY += tan45 * context.measureText(text).width + watermarkInterval;
}
var url = canvas.toDataURL("image/jpeg");
var a = document.createElement("a");
var event = new MouseEvent("click");
a.download = name; // 设置下载的图片名称
a.href = url;
a.dispatchEvent(event);
};
image.src = imgUrl;
}
最终效果
多文件
//fetchAndWatermarkPDF 页面下载调用此方法
// 多个pdf下载加水印多文件
export async function fetchAndWatermarkPDF(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error("Network response was not ok");
const arrayBuffer = await response.arrayBuffer();
return await addWatermarkToPdf(arrayBuffer, "坚持总会胜利");
} catch (error) {
console.error("Error fetching and watermarking PDF:", error);
throw error; // Re-throw to be handled in fetchAndWatermarkPDFs
}
}
// Add watermark to PDF
async function addWatermarkToPdf(arrayBuffer, watermarkText) {
const pdfDoc = await PDFDocument.load(arrayBuffer);
const customFontUrl = require("../../public/font/font.ttf");
const fontBytes = await fetch(customFontUrl).then(res => res.arrayBuffer());
pdfDoc.registerFontkit(fontkit);
const customFont = await pdfDoc.embedFont(fontBytes);
const pages = pdfDoc.getPages();
pages.forEach(page => {
const { width, height } = page.getSize();
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 3; j++) {
page.drawText(watermarkText, {
x: 230 * j,
y: (height / 4) * i,
size: 16,
font: customFont,
color: rgb(0.46, 0.53, 0.6),
rotate: degrees(-45),
opacity: 0.3
});
}
}
});
return pdfDoc.save();
}