手搓下载PDF添加水印

31 阅读1分钟

手搓一个pfd添加水印的功能 虽然是一个很简单的功能,就当记录一下生活。。

//先创建一个js文件 封装一个addWatermarkPdf 函数
//里面传递7个参数 我这7个参数分别为:pdf文件 水印内容 字体大小 文字距离 文字颜色 旋转角度 透明度    插件用的是 jsPDF 
export function addWatermarkPdf(pdf, watermarkText, fontSize, spacing, fontColor, angle, opacity) {
  // 创建一个canvs 元素并获取其2D上下文
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  
  // 测量水印文本的宽度和高度
  const textWidth = context.measureText(watermarkText).width;
  const textHeight = fontSize;
  
  // 获取pdf页面的宽度和高度
  const pageWidth = pdf.internal.pageSize.getWidth();
  const pageHeight = pdf.internal.pageSize.getHeight();
  // 获取pdf页面的宽度和高度
  const numCols = Math.floor(pageWidth / (textWidth + spacing));
  const numRows = Math.floor(pageHeight / (textHeight + spacing));
  
  // 获取pdf页面的宽度和高度
  canvas.width = pageWidth;
  canvas.height = pageHeight;
  
  // 获取pdf页面的宽度和高度
  context.font = `${fontSize}px Arial`;
  context.fillStyle = fontColor;
  context.globalAlpha = opacity;             // 设置水印透明度
  context.rotate((-Math.PI / 180) * angle);  // 旋转角度
  for (let i = 1; i <= pdf.internal.getNumberOfPages(); i++) {
    pdf.setPage(i);
    for (let row = 0; row < numRows; row++) {
      for (let col = 0; col < numCols; col++) {
        const x = col * (textWidth + spacing);
        const y = row * (textHeight + spacing);
        context.fillText(watermarkText, x, y);
      }
    }
    // 获取pdf页面的宽度和高度
    const dataUrl = canvas.toDataURL();
    pdf.addImage(dataUrl, 'PNG', 0, 0, pageWidth, pageHeight);
    context.clearRect(0, 0, pageWidth, pageHeight); // 清除画布
  }
}

还是有很多不足的地方,实现一个简单的下载PDF 添加水印的功能是没有问题的。