项目介绍
pdf-lib是一个强大的javascript库,允许在任何javascript环境中创建和修改pdf文档。无论是前端浏览器环境还是node.js服务器端,它都能提供全面的功能来满足你的需求。
快速启动
要开始使用pdf-lib,首先确保你已经安装了相应的npm包。在命令行中运行以下命令:
npm install --save pdf-lib
或者如果你是yarn的使用者:
yarn add pdf-lib
实现代码
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>pdf watermark example</title>
<script src="https://cdn.bootcdn.net/ajax/libs/pdf-lib/1.17.1/pdf-lib.min.js"></script>
</head>
<body>
<input type="file" id="pdffile" accept="application/pdf">
<button onclick="addwatermark()">添加水印</button>
<a id="downloadlink" style="display:none;">下载pdf</a>
<script>
async function addwatermark() {
const fileinput = document.getelementbyid('pdffile');
const file = fileinput.files[0];
if (!file) {
alert('请选择一个pdf文件');
return;
}
const arraybuffer = await file.arraybuffer();
const pdfdoc = await pdflib.pdfdocument.load(arraybuffer);
const pages = pdfdoc.getpages();
// 获取当前时间并格式化
const now = new date();
const year = now.getfullyear();
const month = string(now.getmonth() + 1).padstart(2, '0');
const day = string(now.getdate()).padstart(2, '0');
const hour = string(now.gethours()).padstart(2, '0');
const minute = string(now.getminutes()).padstart(2, '0');
// 创建水印
const watermarktext = `无敌暴龙兽-${year}-${month}-${day}-${hour}:${minute}-加密`;
const canvas = document.createelement('canvas');
const ctx = canvas.getcontext('2d');
const fontsize = 20;
const textcolor = 'rgba(0, 0, 0, 0.2)';
// 计算文本宽度和高度
ctx.font = `${fontsize}px arial`;
const textmetrics = ctx.measuretext(watermarktext);
const textwidth = textmetrics.width;
const textheight = fontsize;
// 计算旋转后的文本边界
const angle = -math.pi / 4; // 旋转45度
const rotatedwidth = math.abs(textwidth * math.cos(angle)) + math.abs(textheight * math.sin(angle));
const rotatedheight = math.abs(textheight * math.cos(angle)) + math.abs(textwidth * math.sin(angle));
// 设置canvas大小
canvas.width = rotatedwidth + 20; // 增加一些边距
canvas.height = rotatedheight + 20;
// 绘制水印文本
ctx.clearrect(0, 0, canvas.width, canvas.height);
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(angle);
ctx.font = `${fontsize}px arial`;
ctx.fillstyle = textcolor;
ctx.textalign = 'center';
ctx.textbaseline = 'middle';
ctx.filltext(watermarktext, 0, 0);
// 将canvas转换为image对象
const image = new image();
image.src = canvas.todataurl('image/png');
// 添加水印到每一页pdf
for (const page of pages) {
const { width, height } = page.getsize();
// 计算新的水印尺寸,以便它可以跨越页面的两个相邻边缘
const cornermargin = 50; // 角落与页面边缘之间的最小距离
const cornersizemultiplier = 0.5; // 控制水印相对于页面尺寸的比例
const scale = 1; // 水印缩放比例
const cornerwidth = math.min(width, height) * cornersizemultiplier * scale;
const cornerheight = cornerwidth; // 假设是正方形水印
// 计算水印的新位置,使其跨越页面的两个相邻边缘
const positions = [
{ x: cornermargin, y: cornermargin }, // 左上角
{ x: width - cornerwidth - cornermargin, y: cornermargin }, // 右上角
{ x: cornermargin, y: height - cornerheight - cornermargin }, // 左下角
{ x: width - cornerwidth - cornermargin, y: height - cornerheight - cornermargin } // 右下角
];
// 需要重新创建水印图像以匹配新尺寸
const newcanvas = document.createelement('canvas');
const newctx = newcanvas.getcontext('2d');
newcanvas.width = cornerwidth;
newcanvas.height = cornerheight;
// 复制旧水印到新画布
newctx.drawimage(canvas, 0, 0, cornerwidth, cornerheight);
// 将新画布转换回image对象
const newimage = new image();
newimage.src = newcanvas.todataurl('image/png');
// 嵌入新水印到pdf文档
const newimg = await pdfdoc.embedpng(newimage.src);
for (const pos of positions) {
page.drawimage(newimg, {
x: pos.x,
y: pos.y,
width: newimg.width,
height: newimg.height,
});
}
}
// 保存修改后的pdf
const pdfdatauri = await pdfdoc.saveasbase64({ datauri: true });
const downloadlink = document.getelementbyid('downloadlink');
downloadlink.href = pdfdatauri;
downloadlink.download = 'watermarked.pdf';
downloadlink.click();
}
</script>
</body>
</html>
效果图

到此这篇关于使用pdf-lib.js实现pdf添加自定义水印功能的文章就介绍到这了,更多相关pdf-lib实现pdf添加自定义水印内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论