对于已存在的pdf需要如何添加水印呢?前端也可实现该功能。
利用pdf-lib库即可实现。
官网地址:https://pdf-lib.js.org/
源码地址:https://github.com/Hopding/pdf-lib
注意:如是添加图片水印,该水印图片需为网络图片
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/pdf-lib@1.4.0"></script>
<script src="https://unpkg.com/downloadjs@1.4.7"></script>
</head>
<body>
<p>Click the button to modify an existing PDF document with <code>pdf-lib</code></p>
<button onclick="modify()">Modify PDF</button>
<p class="small">(Your browser will download the resulting file)</p>
</body>
<style>
body {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
p {
font-family: helvetica;
font-size: 24px;
text-align: center;
margin: 25px;
}
.small {
font-family: helvetica;
font-size: 18px;
text-align: center;
margin: 25px;
}
button {
background-color: #008CBA;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
font-size: 16px;
}
</style>
<script>
const { degrees, PDFDocument, rgb, StandardFonts } = PDFLib
async function modify() {
// Fetch an existing PDF document
const url = 'xxx';
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())
// Load a PDFDocument from the existing PDF bytes
const pdfDoc = await PDFDocument.load(existingPdfBytes)
// Embed the Helvetica font
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
//为第一页pdf添加文字水印
// Get the first page of the document
const pages = pdfDoc.getPages()
//const firstPage = pages[0]
// Get the width and height of the first page
//const { width, height } = firstPage.getSize()
// Draw a string of text diagonally across the first page
// firstPage.drawText('hello', {
// x: 5,
// y: height / 2 + 300,
// size: 50,
// font: helveticaFont,
// color: rgb(0.2, 0.1, 0.1),
// rotate: degrees(-45),
// })
//为所有pdf添加图片水印
const img ="http://xxx/水印.png";
const ImgCover = await fetch(img).then((res) => res.arrayBuffer());
const eleImgCover = await pdfDoc.embedPng(ImgCover);
pages.forEach((item) => {
item.drawImage(eleImgCover, {
x: item.getWidth() / 2 - eleImgCover.width / 4,
y: item.getHeight() / 2,
width: eleImgCover.width/2,
height: eleImgCover.height/2,
});
});
const pdfBytes = await pdfDoc.save();
download(pdfBytes,test.pdf, "application/pdf");
}
</script>
</html>