Skip to content

Instantly share code, notes, and snippets.

@whchi
Created March 6, 2025 03:07
Show Gist options
  • Select an option

  • Save whchi/83c9e2d1fba15f6c29ab7b135b6350ea to your computer and use it in GitHub Desktop.

Select an option

Save whchi/83c9e2d1fba15f6c29ab7b135b6350ea to your computer and use it in GitHub Desktop.
adding watermark to pdf using sharp.js & pdf-lib.js
async createWaterMark({
width,
height,
text,
fontSize,
fontColor,
opacity,
}: CreateWaterMarkDto) {
const svg = `
<svg width="${width}" height="${height}">
<rect width="100%" height="100%" fill="transparent" />
<text x="50%" y="50%"
dominant-baseline="middle"
text-anchor="middle"
font-family="Arial,SimSun"
font-size="${fontSize}"
opacity="${opacity}"
fill="${fontColor}">
${text}
</text>
</svg>
`;
return sharp(Buffer.from(svg)).png().toBuffer();
}
async addWaterMarkToPdf({
buffer,
watermarkImageBytes,
watermarkOptions,
}: AddWaterMarkToDocumentDto): Promise<Buffer> {
const {
opacity = 0.8,
scale = 1,
} = watermarkOptions;
try {
const pdfDoc = await PDFDocument.load(buffer);
const pages = pdfDoc.getPages();
const watermarkImage = await pdfDoc.embedPng(watermarkImageBytes);
const { width: imgWidth, height: imgHeight } = watermarkImage.scale(scale);
pages.forEach(page => {
const { width, height } = page.getSize();
const pageRotation = page.getRotation().angle;
let x: number,
y: number,
rotation: number;
switch (pageRotation) {
case 0:
default:
x = 0;
y = height - imgHeight;
if (y < 0) y = 0;
rotation = 0;
break;
case 90:
x = width - imgHeight; // wmHeight=20
if (x < 0) x = 0;
y = height;
if (y > height) y = height;
rotation = -90;
break;
case 180:
x = width;
y = imgHeight;
if (x > width) x = width;
if (y > height) y = height;
rotation = -180;
break;
case 270:
x = imgHeight;
y = 0;
rotation = -270;
break;
}
page.drawImage(watermarkImage, {
x,
y,
width: imgWidth,
height: imgHeight,
opacity,
rotate: degrees(rotation),
});
});
return Buffer.from(await pdfDoc.save());
} catch (error) {
const message = 'Error occurred while adding watermark to PDF';
this.logger.error(message, error);
throw new InternalServerErrorException(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment