Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
JavaScript

How to Add Image Watermarks to PDFs in Node.js

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

To watermark an existing PDF in Node.js, use pdf-lib: load the PDF, embed a PNG or JPEG, draw that image on each page you want marked, and save the result. The example below places a faint, proportionally scaled image in the center of every page. You can change the placement, size, opacity, rotation, and target pages to fit your document.

Use pdf-lib to watermark an existing PDF

pdf-lib documents loading and modifying existing PDFs, embedding PNG or JPEG image data, and drawing images on pages. That makes it a direct fit when you already have a PDF and want to add a logo or ownership mark. The steps below use Node’s built-in file system API and an ES module import. Check your project’s module configuration if it uses CommonJS rather than ES modules.

  1. Install the package with npm install pdf-lib.
  2. Put the source PDF and a PNG watermark image beside the script, named input.pdf and watermark.png.
  3. Save the script below as watermark.mjs and run node watermark.mjs.
  4. Open watermarked.pdf and inspect representative pages before using the output in a production workflow.
import fs from 'node:fs/promises';
import { PDFDocument, degrees } from 'pdf-lib';

async function main() {
  const pdfBytes = await fs.readFile('input.pdf');
  const imageBytes = await fs.readFile('watermark.png');

  const pdfDoc = await PDFDocument.load(pdfBytes);
  const watermark = await pdfDoc.embedPng(imageBytes);

  for (const page of pdfDoc.getPages()) {
    const { width, height } = page.getSize();
    const imageSize = watermark.scaleToFit(width * 0.25, height * 0.25);

    page.drawImage(watermark, {
      x: (width - imageSize.width) / 2,
      y: (height - imageSize.height) / 2,
      width: imageSize.width,
      height: imageSize.height,
      rotate: degrees(0),
      opacity: 0.2,
    });
  }

  const outputBytes = await pdfDoc.save();
  await fs.writeFile('watermarked.pdf', outputBytes);
}

main().catch((error) => {
  console.error('Could not watermark the PDF:', error);
  process.exitCode = 1;
});

The sample embeds the image once, then draws it on every page returned by getPages(). It uses each page’s own dimensions, so pages with different sizes are handled individually. The 25% fit box and 20% opacity are starting values, not universal recommendations; adjust them after reviewing the output at normal reading size and in print.

Control the image, position, size, and appearance

Choose PNG or JPEG

For a PNG image, use embedPng(imageBytes), as in the example. For a JPEG, use embedJpg(imageBytes) instead. The documented embedding methods also accept base64 strings or data URIs, as well as Uint8Array and ArrayBuffer inputs. Node’s fs.readFile() returns bytes suitable for the example.

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.
#1 Best Overall
MobiPDF Ultimate - All-in-One PDF Reader & Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | 1-Year Subscription | 1 Windows PC + 2 Mobile Devices | 1 User
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs.
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs.
  • 1 Year License for 1 Windows & 2 Mobile (Android and/or iOS) devices.

A PNG is a practical choice for a logo when you need transparent areas around its visible mark. pdf-lib’s documentation establishes PNG support but does not establish behavior for every transparency edge case, so inspect your chosen image in the saved PDF rather than assuming every source image will render as intended.

Set placement deliberately

drawImage takes explicit x, y, width, and height values. The sample centers the image by subtracting its fitted dimensions from the page dimensions. To put a logo in a corner, replace the centering expressions with your chosen offsets, then test across portrait, landscape, and differently sized pages.

scaleToFit(maxWidth, maxHeight) returns dimensions that fit inside the supplied box while preserving the image’s proportions. This is safer than assigning a width and height independently when the source logo is not square. If you want a larger or smaller mark, change the fit-box multipliers; if you want a diagonal mark, set rotate to a value such as degrees(35) and inspect the result for clipping.

Change opacity and rotation

The drawing options support opacity and rotate. Lower opacity makes the image less prominent; zero rotation leaves it level. The example imports degrees from pdf-lib and passes degrees(0). Use a modest opacity for a watermark intended to sit behind readable content, but choose the value from a visual review rather than treating the example’s value as a standard.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Scrivar PDF Pro - Organize, Edit, Compress, Convert, Merge, eSign, OCR & 30+ tools | Lifetime License
  • EVERY PDF TOOL UNLOCKED - 30+ tools in one app: edit text and images, convert, merge, split, compress, sign, OCR, redact, watermark, batch process, and more. No feature gates, no upsells, nothing held back.
  • PAY ONCE, OWN FOREVER — A one-time purchase, not a subscription. Other apps runs $240/year — Scrivar is yours for life, with free updates included.
  • UNLIMITED eSIGN, BUILT IN — Send contracts and forms for signature and track every step. Recipients sign in their browser with no account or app needed. Replace DocuSign and save hundreds a year.
  • PC, MAC, AND WEB — Install on any Win 10/11 PC or macOS 11+ Mac (Intel or Apple Silicon), or work in your browser at scrivar.com. Same tools, same account, everywhere you work.
  • OCR + FULL OFFICE CONVERSION — Turn scanned documents into searchable, selectable text, and convert PDFs to and from Word, Excel, and PowerPoint with formatting kept intact.

Apply the image to selected pages

To mark every page, keep the loop over pdfDoc.getPages(). To limit the operation, select pages from that array before drawing. Array indexes are zero-based in JavaScript, so a user-facing page number of 1 corresponds to index 0. For example, to draw only on the first page, replace the loop with const page = pdfDoc.getPages()[0]; and perform the same sizing and drawImage calls on that page. Check that the selected page exists before using it, especially when page selection comes from user input.

When PDFKit is a better fit

If your application is creating a PDF rather than modifying an existing one, PDFKit is another option. Its documentation describes JPEG and PNG images supplied as a path, buffer, or base64 data URI, with sizing controls such as width, height, scale, and a fit box. It also supports absolute positioning with x and y; without those coordinates, an image is placed at the current point in the text flow.

The choice depends on the workflow: pdf-lib explicitly documents modifying existing PDFs, while PDFKit’s documentation focuses on creating and laying out documents. Both document PNG and JPEG support. These facts do not establish a universal winner or a performance comparison; choose based on whether you need to edit a supplied PDF or build a new one.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a PDF watermarking library. It does not replace the pdf-lib steps above for adding an image to an existing PDF. If the separate task is capturing a website as an image, a single request can return a screenshot:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for its request options. ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides screenshot, page-information, and PDF-capture tools for AI agents. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. For website capture, visit ScreenshotNeo or sign up for 1,000 free screenshots a month with no card.

Troubleshooting and operational checks

The script cannot find an input file

fs.readFile() resolves relative paths from the process’s current working directory, which may differ from the script’s directory. Run Node from the folder containing the files, or provide explicit paths. Confirm the filenames and letter case match exactly.

The image embedding call fails

Check that the file is actually a supported PNG or JPEG and that the method matches its format: embedPng for PNG, embedJpg for JPEG. A renamed file does not convert its contents. If the input is base64, provide a supported base64 string or data URI rather than passing an unrelated string as though it were a local path.

The watermark is misplaced or too large

Confirm that the calculation uses the current page’s width and height, and that the image’s fitted dimensions are used consistently for both positioning and drawing. Review pages of different orientations and sizes; a placement tuned on one page may not look right on another. Reduce the fit-box multipliers or opacity if the mark competes with the document content.

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

The output is missing or cannot be opened

Ensure the script reaches pdfDoc.save() and that the process has permission to write watermarked.pdf in the destination folder. The example’s error handler prints the failure and sets a nonzero process exit code. Keep the source file unchanged and test the generated output in a PDF reader before replacing any original.

Rank #4
Corel PDF Fusion - PDF Creator Toolkit [PC Disc]
  • Assemble, edit, and create PDFs with this easy to use, all in one PDF creator
  • Open and view over 100 file types, without purchasing additional software
  • Drag and drop multiple different file types into one PDF document
  • Easily add new text and comments to PDFs
  • Share your created documents with anyone in PDF, PDF/A, XPS or Microsoft Word formats

Large or unusual PDFs need validation

PDF size, processing time, and compatibility depend on the specific documents and runtime; the cited documentation does not provide benchmark figures or guarantee behavior for encrypted files, digital signatures, or every unusual PDF feature. Test with representative inputs, including the page sizes, image type, and orientation used in your application. Treat a signed document as a special case: do not assume that editing and saving it preserves a prior signature’s validity.

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

Performance, reliability, and cost considerations

This workflow reads the PDF and image into memory, loads the document, adds the image to selected pages, and serializes a new PDF. For large input files or batches, measure memory use and elapsed time with your own representative documents; no performance benchmark is established here. Embedding once and reusing the same image object across the page loop avoids repeating the embed call in the example.

For reliable processing, write to a new output path rather than overwriting the source, handle read, load, embed, and save errors, and validate output before making it available to users. Keep the original image and PDF available for retries. If your application accepts uploads, also apply the file validation and resource limits appropriate to your service; this example is a local-file workflow, not an upload security policy.

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

pdf-lib is a software dependency installed through npm; the documented approach does not involve per-page service billing. pdf-lib’s documentation does not establish a specific package version or guarantee behavior across all PDFs, so check the package’s current documentation and verify your project’s import style and sample output.

Best Value
MobiOffice Lifetime 4-in-1 Productivity Suite for Windows | Lifetime License | Includes Word Processor, Spreadsheet, Presentation, Email + Free PDF Reader
  • Not a Microsoft Product: This is not a Microsoft product and is not available in CD format. MobiOffice is a standalone software suite designed to provide productivity tools tailored to your needs.
  • 4-in-1 Productivity Suite + PDF Reader: Includes intuitive tools for word processing, spreadsheets, presentations, and mail management, plus a built-in PDF reader. Everything you need in one powerful package.
  • Full File Compatibility: Open, edit, and save documents, spreadsheets, presentations, and PDFs. Supports popular formats including DOCX, XLSX, PPTX, CSV, TXT, and PDF for seamless compatibility.
  • Familiar and User-Friendly: Designed with an intuitive interface that feels familiar and easy to navigate, offering both essential and advanced features to support your daily workflow.
  • Lifetime License for One PC: Enjoy a one-time purchase that gives you a lifetime premium license for a Windows PC or laptop. No subscriptions just full access forever.

Frequently Asked Questions

Can an image watermark be added to only the first page?

Yes. Select the first page from pdfDoc.getPages() and draw the embedded image on that page rather than looping over the full page array.

Can I use the same watermark image on different page sizes?

Yes. Calculate placement and fit dimensions from each page’s own size, as the example does. Review the result on each page geometry used by your PDFs.

Does adding a watermark make it impossible to remove or copy?

No such protection is established by this workflow. It draws an image into the PDF; do not treat that as a guarantee against removal or copying.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.