Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
PDFs
Categories

How do I add a DRAFT watermark to every page of a PDF in Node.js with pdf-lib?

Load the existing PDF, loop over every page, and draw semi-transparent rotated text on each one. The script below also builds a two page test PDF so you can run it as is.

const { PDFDocument, StandardFonts, rgb, degrees } = require("pdf-lib");

async function addWatermark(pdfBytes, text) {
  const pdf = await PDFDocument.load(pdfBytes);
  const font = await pdf.embedFont(StandardFonts.HelveticaBold);
  const size = 72;
  const textWidth = font.widthOfTextAtSize(text, size);
  const angle = Math.PI / 4;

  for (const page of pdf.getPages()) {
    const { width, height } = page.getSize();
    page.drawText(text, {
      x: width / 2 - (textWidth / 2) * Math.cos(angle),
      y: height / 2 - (textWidth / 2) * Math.sin(angle),
      size,
      font,
      color: rgb(0.75, 0.75, 0.75),
      opacity: 0.5,
      rotate: degrees(45),
    });
  }
  return pdf.save();
}

(async () => {
  const src = await PDFDocument.create();
  src.addPage([612, 792]);
  src.addPage([612, 792]);
  const out = await addWatermark(await src.save(), "DRAFT");
  const check = await PDFDocument.load(out);
  console.log("pages:", check.getPageCount(), "bytes>0:", out.length > 0);
})();

How it works

embedFont adds a standard font to the document, and widthOfTextAtSize measures the text so you can center it. drawText accepts x, y, size, font, color, opacity and rotate, all documented on the pdf-lib drawText options page.

In the generated PDF, the rotated text's origin sits at the (x, y) you pass, and the baseline runs off at the rotation angle from there. That is why the code subtracts half the text width along the 45 degree direction from the page center. Without that offset the watermark sits off to one side.

Caveats

The watermark is drawn on top of existing page content. It labels a document as a draft but does not protect it, since a PDF editor can remove it. Adjust size and opacity to keep the underlying text readable.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms
Marketing Mode