Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use pdf-lib to open the existing PDF, draw text on each page, and save a new file. The library runs in Node.js and exposes controls for the watermark’s position, font, size, color, and opacity. The complete example below adds a centered, semi-transparent “CONFIDENTIAL” label to every page without changing the original file.

What you need

  • A current Node.js project using ECMAScript modules (the example uses import).
  • An input PDF that your application can read.
  • The pdf-lib package installed from npm.

Create a project and install the dependency:

mkdir pdf-watermark
cd pdf-watermark
npm init -y
npm install pdf-lib

Add "type": "module" to package.json, or use the equivalent CommonJS imports for your project. Put the source PDF in the project directory as input.pdf.

Add a watermark to every page

This script follows the documented pdf-lib workflow: read the bytes, load a PDFDocument, obtain the pages, draw text, serialize the document, and write the result.

import { readFile, writeFile } from 'node:fs/promises';
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';

const input = await readFile('input.pdf');
const pdfDoc = await PDFDocument.load(input);
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);

const text = 'CONFIDENTIAL';
const size = 24;

for (const page of pdfDoc.getPages()) {
  const { width, height } = page.getSize();
  const textWidth = font.widthOfTextAtSize(text, size);

  page.drawText(text, {
    x: (width - textWidth) / 2,
    y: height / 2,
    size,
    font,
    color: rgb(0.7, 0.1, 0.1),
    opacity: 0.35,
  });
}

const output = await pdfDoc.save();
await writeFile('watermarked.pdf', output);

console.log('Wrote watermarked.pdf');

Save it as watermark.mjs and run:

node watermark.mjs

The original input.pdf remains untouched. watermarked.pdf contains the additional text on every page, including pages with different sizes because the coordinates are calculated from each page’s own dimensions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Control position and appearance

Center the label

page.getSize() returns the page width and height in PDF points. font.widthOfTextAtSize() estimates the rendered width, so subtracting that width from the page width and dividing by two centers the text horizontally. The sample uses height / 2 for the vertical coordinate; adjust that value for a footer, header, or another fixed location.

Change text, color, and transparency

Set text to the wording your policy requires. The rgb() values range from 0 to 1; for example, rgb(0, 0, 0) is black and rgb(1, 1, 1) is white. Lower opacity makes the watermark less intrusive. Preview representative pages on screen and on paper because contrast that looks subtle on a monitor can be too faint when printed.

Use a different standard font

pdf-lib exposes standard PDF fonts such as Helvetica, Times Roman, and Courier through StandardFonts. Replace StandardFonts.Helvetica with the standard font that best fits your document.

Support a custom font or non-Latin text

If the watermark contains characters outside the selected standard font’s coverage, embed a font file instead. pdf-lib’s documented custom-font integration requires registering @pdf-lib/fontkit and embedding the font bytes before calling drawText:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
npm install pdf-lib @pdf-lib/fontkit
import { readFile } from 'node:fs/promises';
import { PDFDocument } from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';

const pdfDoc = await PDFDocument.load(await readFile('input.pdf'));
pdfDoc.registerFontkit(fontkit);
const fontBytes = await readFile('fonts/NotoSans-Regular.ttf');
const font = await pdfDoc.embedFont(fontBytes);

// Use this font in page.drawText({ font, ... })

Choose a font licensed for your use, and verify the output in the PDF viewers your recipients use. A font that lacks a required glyph can produce missing or incorrect characters.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Watermark only selected pages

getPages() returns an array, so you can select pages by index. PDF page indexes are zero-based:

const pages = pdfDoc.getPages();
for (const index of [0, 2, 4]) {
  const page = pages[index];
  if (!page) continue;
  page.drawText('DRAFT', {
    x: 36,
    y: 36,
    size: 18,
    font,
    color: rgb(0.2, 0.2, 0.2),
    opacity: 0.4,
  });
}

For a contiguous range, loop from the first index through the last and check that each index exists. If the source can be empty or shorter than expected, always guard against an undefined page.

Build a reusable watermark function

Putting the operation in a function makes it easier to process uploads, jobs, or multiple files:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { readFile, writeFile } from 'node:fs/promises';
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';

export async function addWatermark(inputPath, outputPath, label) {
  const pdfDoc = await PDFDocument.load(await readFile(inputPath));
  const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
  const size = 24;

  for (const page of pdfDoc.getPages()) {
    const { width, height } = page.getSize();
    const textWidth = font.widthOfTextAtSize(label, size);
    page.drawText(label, {
      x: Math.max(0, (width - textWidth) / 2),
      y: height / 2,
      size,
      font,
      color: rgb(0.7, 0.1, 0.1),
      opacity: 0.35,
    });
  }

  await writeFile(outputPath, await pdfDoc.save());
}

await addWatermark('input.pdf', 'watermarked.pdf', 'CONFIDENTIAL');

For untrusted uploads, write to a controlled temporary directory, impose your own file-size and execution limits, and remove temporary files after the job. Keep the output path distinct from the input until validation succeeds.

Diagonal and advanced layouts

A diagonal watermark can be useful, but the exact text-transform options depend on the pdf-lib version you install. The documentation establishes text drawing and styling, not a single production recipe for every rotated layout. Check the API reference for your installed version before relying on a rotation option, then test pages with portrait and landscape dimensions. If rotation is not available in your version, place the label horizontally or draw it in a pre-rendered asset with a tool that supports the transform you need.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

For repeated labels, headers, or footers, calculate coordinates from width and height rather than hard-coding one page size. Leave a margin so the label does not run into trim or printer margins.

Common failures and fixes

“Cannot use import statement outside a module”

Node is treating the file as CommonJS. Add "type": "module" to package.json, use an .mjs extension, or convert the imports to your project’s CommonJS convention.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The output is blank or the load fails

Confirm that the input path points to a PDF and that the process has read permission. A truncated, malformed, encrypted, or otherwise unusual file may not load successfully. Catch the exception, preserve the original upload, and report the file as unsupported rather than overwriting it.

The watermark is invisible

Increase opacity, choose a contrasting color, increase size, and verify that x and y fall inside the page bounds. Remember that PDF coordinates start at the lower-left in the usual coordinate system, so a small y value is near the bottom.

Characters display as boxes or disappear

The selected font does not contain those glyphs. Embed a suitable font with @pdf-lib/fontkit, and check the font’s license and coverage.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Only some pages have a watermark

Ensure the drawing call is inside the loop over pdfDoc.getPages(). If you intentionally selected indexes, remember that they start at zero and that a missing index is skipped.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Forms, encryption, or complex PDFs behave differently

The reviewed documentation confirms existing-document modification and text drawing, but it does not establish universal behavior for every encrypted, malformed, form-heavy, or unusually structured PDF. Validate the actual files your service receives and inspect the result in the target viewers before promising compatibility.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and output checks

  • Embedding one font before the page loop avoids repeating the same embedding work for every page.
  • Process large files in a queue or worker when request timeouts are a concern; the complete document is loaded and serialized in memory by this pattern.
  • Write to a temporary output, reopen or otherwise validate it in your pipeline, then atomically move it into place so a failed save cannot replace a good file.
  • Test a representative set: different page sizes, many-page files, scanned pages, selectable text, custom glyphs, and printed output.
  • Keep pdf-lib and your Node.js runtime maintained according to your organization’s dependency policy. No independent performance benchmark or Node.js version matrix is established here.

Or skip the browser setup

If your workflow also needs a clean image or PDF capture of a published, watermarked page, ScreenshotNeo provides a single HTTP request instead of maintaining a browser. It accepts cookie and consent banners as a visitor, removes more than 60 known consent platforms plus newsletter popups and chat widgets before capture, and lets you turn each cleanup step off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. A cURL request looks like this:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots, and every feature is included on every plan. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently asked questions

Does drawing a watermark make a PDF impossible to edit?

No. This operation adds page content; it is not a security or digital-rights control. Readers may still edit, copy, or remove content with tools that support those operations.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Can I preserve the original PDF?

Yes. Read the source and write a separate output path, as the examples do. Keep the original until the new file has passed your validation checks.

Is a watermark applied to annotations or attachments?

The documented method draws text on pages. It does not establish behavior for every annotation, attachment, form, or encrypted-document feature, so test those structures in your own files.

Frequently Asked Questions

Can I preserve the original PDF?

Yes. Read the source and write a separate output path, then validate the new file before replacing or distributing anything.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is a watermark applied to annotations or attachments?

The method draws text onto pages; behavior for every annotation, attachment, form, or encrypted structure is not established and should be tested with your files.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.