-
Notifications
You must be signed in to change notification settings - Fork 4
/
watermark.js
85 lines (71 loc) · 2.27 KB
/
watermark.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const { PDFDocument, degrees } = require("pdf-lib");
const { writeFileSync, readFileSync } = require("fs");
async function PDFWatermark(options) {
const { text, pdf_path, image_path, output_dir, imageOption = {}, textOption = {} } = options;
if (!pdf_path) {
throw Error("Please add pdf_path in options.");
}
// load pdf
const document = await PDFDocument.load(readFileSync(pdf_path), { ignoreEncryption: true });
// get pages and number of pages
const pages = document.getPages();
const numberOfPages = pages.length;
// loop throgh all pages
if (text) {
for (let i = 0; i < numberOfPages; i++) {
const page = pages[i];
const { width, height } = page.getSize();
// diagonally rotate text
if (textOption?.diagonally == true) {
textOption.rotate = degrees(-45);
textOption.x = width / 2 - text.length * 9;
textOption.y = height / 2 + 200;
}
// text watermark
await page.drawText(text, {
x: width / 2 - text.length * 9, // center with left padding for text
y: height / 2 - 20,
size: 12,
opacity: 0.6,
...textOption,
});
}
}
// image watermark
if (image_path) {
// load image
const emblemImageBytes = readFileSync(image_path);
const image = await document.embedPng(emblemImageBytes);
const pngDims = image.scale(0.5);
// loop throgh all pages
for (let i = 0; i < numberOfPages; i++) {
const page = pages[i];
const { width, height } = page.getSize();
// diagonally rotate text
if (imageOption?.diagonally == true) {
imageOption.rotate = degrees(-45);
imageOption.x = width / 2;
imageOption.y = height / 2 + 200;
}
await page.drawImage(image, {
x: width / 2 - pngDims.width / 2 + 15,
y: height / 2 - pngDims.height - 20,
width: pngDims.width,
height: pngDims.height,
opacity: 0.6,
...imageOption,
});
}
}
// write to file
writeFileSync(output_dir || pdf_path, await document.save());
}
// (async function () {
// await PDFWatermark({
// pdf_path: "./newsletter.pdf",
// text: "Gentech",
// output_dir: "./output.pdf",
// image_path: "./everest.png",
// });
// })();
module.exports = PDFWatermark;