实现PDF加水印以及自定义水印样式
<template><div><button @click="previewHandle">预览</button><button @click="downFileHandle">下载</button><el-input v-model="watermarkText" /><el-input v-model.number="watermarkrotate" /><iframe id="log_frame" class="log-iframe" frameborder="0" :src="pdfPreviewUrl"></iframe></div>
</template><script setup>
import { ref, reactive, onMounted } from 'vue'
import { degrees, PDFDocument, rgb, StandardFonts } from "pdf-lib";
import fontkit from '@pdf-lib/fontkit'const pdfFileEnd = ref('http://111.229.162.189:8003/file/construction/2024_01_08/三高共管对接接口(5)_14ba6d68.pdf')
const pdfPreviewBlob = ref()
const pdfPreviewUrl = ref('/pdf/web/viewer.html?file=http://111.229.162.189:8003/file/construction/2024_01_08/三高共管对接接口(5)_14ba6d68.pdf')const watermarkText = ref('2024-01-17')
const watermarkrotate = ref(45)
const addWatermark = async (rotate) => {try {const existingPdfBytes = await fetch(pdfFileEnd.value).then((res) => res.arrayBuffer());const pdfDoc = await PDFDocument.load(existingPdfBytes);const pages = pdfDoc.getPages();for (let i = 0; i < pages.length; i++) {const noPage = pages[i];const { width, height } = noPage.getSize();for (let i = 0; i < 10; i++) {for (let j = 0; j < 3; j++) {noPage.drawText(watermarkText.value, {x: 230 * j + 36,y: (height / 4) * i + 20,size: 20,color: rgb(0.46, 0.53, 0.6),rotate: degrees(rotate),opacity: 0.3,});}}}const pdfBytes = await pdfDoc.save();pdfPreviewBlob.value = pdfBytes} catch (error) {console.log("文件下载失败!");}
}
const previewHandle = async () => {console.log(typeof(watermarkrotate.value));await addWatermark(watermarkrotate.value)const blob = new Blob([pdfPreviewBlob.value], { type: 'application/pdf' });const url = window.URL.createObjectURL(blob);pdfPreviewUrl.value = '/pdf/web/viewer.html?file=' + url
}
const downFileHandle = () => {var blob = new Blob([pdfPreviewBlob.value], { type: "application/pdf" });var link = document.createElement("a");link.href = window.URL.createObjectURL(blob);link.download = '水印pdf';link.click();
}onMounted(() => {addWatermark()
})
</script><style lang="scss" scoped>
.log-iframe {width: 800px;height: 520px;
}
</style>