const { PDFDocument, StandardFonts, PDFFont, degrees, rgb, PDFNumber, PDFPage } = require('pdf-lib');
const fs = require("fs");
const rbgWrapper = (red, green, blue) => rgb(red / (255 / 100) / 100, green / (255 / 100) / 100, blue / (255 / 100) / 100);
// CONSTANTS
const STAMP_COLOR = [85, 0, 171];
// Method for create PDF with stamp
const createStampDoc = async () => {
const newPDF = await PDFDocument.create();
const width = 250;
// Embed the Helvetica font
const TimesRoman = await newPDF.embedFont(StandardFonts.TimesRoman)
// Creating page for stamp
const page = newPDF.addPage([width, 100]);
const drawStamp = (page, x, y) => {
let curY = y;
curY += 10;
page.moveTo(x, curY);
page.drawText("TEXT ONE", {
font: TimesRoman,
size: 10,
color: rbgWrapper(...STAMP_COLOR)
});
curY += 10;
page.moveTo(x, curY);
page.drawText("TEXT TWO", {
font: TimesRoman,
size: 10,
color: rbgWrapper(...STAMP_COLOR)
});
// Border of stamp
const height = curY - y + 10;
page.drawRectangle({
x: x,
y: y,
width: width,
height: height,
borderColor: rbgWrapper(...STAMP_COLOR),
borderWidth: 1,
opacity: 0.3,
color: rbgWrapper(255, 255, 255)
});
page.setHeight(height);
return { width, height };
};
drawStamp(page, 0, 0);
return newPDF;
};
async function main() {
// Creating new main PDF file
const mainPDF = await PDFDocument.create();
mainPDF.addPage([350, 400]);
mainPDF.addPage([350, 400]);
const stampPDF = await createStampDoc();
const [copiedStampPage] = await mainPDF.copyPages(stampPDF, [0]);
const embeddedPage = await mainPDF.embedPage(copiedStampPage);
// In each page embedding stamp page
const pages = mainPDF.getPages();
for (const page of pages) {
await page.drawPage(embeddedPage, { x: 100, y: 100, rotate: degrees(20), opacity: 1 });
}
const binaryFileWithStamp = await mainPDF.save();
fs.writeFileSync("stamp.pdf", Buffer.from(binaryFileWithStamp));
}
main();