惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
Martin Fowler
Martin Fowler
月光博客
月光博客
AI
AI
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
CXSECURITY Database RSS Feed - CXSecurity.com
WordPress大学
WordPress大学
GbyAI
GbyAI
L
Lohrmann on Cybersecurity
O
OpenAI News
Schneier on Security
Schneier on Security
P
Palo Alto Networks Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Troy Hunt's Blog
V2EX - 技术
V2EX - 技术
W
WeLiveSecurity
L
LINUX DO - 最新话题
人人都是产品经理
人人都是产品经理
S
Security Affairs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
Arctic Wolf
Recorded Future
Recorded Future
Microsoft Security Blog
Microsoft Security Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
G
GRAHAM CLULEY
N
Netflix TechBlog - Medium
TaoSecurity Blog
TaoSecurity Blog
C
Check Point Blog
Scott Helme
Scott Helme
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
PCI Perspectives
PCI Perspectives
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Vercel News
Vercel News
The Hacker News
The Hacker News
Y
Y Combinator Blog
Latest news
Latest news
SecWiki News
SecWiki News
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cisco Blogs
博客园_首页
H
Hackread – Cybersecurity News, Data Breaches, AI and More
宝玉的分享
宝玉的分享
L
LINUX DO - 热门话题

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

Learn Command Line Interface (CLI) Development with Dart: From Zero to a Fully Published Developer Tool How to Build a Live Options Database in Python – A Complete Guide How to Migrate to S3 Native State Locking in Terraform How to Use SCons to Build Software Projects [Full Handbook] How to Run Open Source LLMs Locally and in the Cloud QuRT: The Real-Time OS Inside Your Phone's Processor [Full Handbook] The Real Infrastructure Behind Remote Work (It’s Not Just Wi-Fi) The Lithography Handbook: Machines, Markets, and the Next Wave of Semiconductor Startups ITCM vs DTCM vs DDR: Embedded Memory Types Explained [Full Handbook] AI Paper Review: Improving Language Understanding by Generative Pre-Training (GPT-1) How to Build a Market Research Copilot with MCP and Python [Full Handbook] How to Build a Scoped Note-Taking API with Django Rest Framework and SimpleJWT The Complete SOC 2 Type II Implementation Handbook for Engineers: A Month-by-Month Roadmap with Real Commands Mastering the JavaScript Event Loop Data Science Insights: Why the Mean Lies When Handling Messy Retail Data How to Build High-Ranking SEO Landing Page How to Query Data in DynamoDB Using .Net How to Unblock Your AI PR Review Bottleneck: A Tech Lead’s Guide to Building a Codebase-Aware Reviewer How to Navigate Microservices as a Frontend Engineer How to Compress PDF Files in the Browser Using JavaScript (Step-by-Step) Stanford's youngest instructor talks InfoSec, AI, and catching cheaters - Rachel Fernandez interview [Podcast #217] Product Experimentation with Propensity Scores: Causal Inference for LLM-Based Features in Python How to Build a Multi-Agent AI System with LangGraph, MCP, and A2A [Full Book] How to Land Your First Cloud or DevOps Role: What Hiring Managers Actually Look For How to Deploy a Serverless Spam Classifier Using Scikit-Learn, AWS Lambda, & API Gateway How to Dockerize a Go Application – Full Step-by-Step Walkthrough Learn Hardware, Cloud, DevOps, Networking, Security, Databases, DNS, Git, and Linux Inside TreeHacks 2026, Stanford’s Elite Student Hakc Inside Stanford’s Elite Student Hackathon [Full Documentary] How to Measure Your AI Citation Rate Across ChatGPT, Perplexity, and Claude How to Deploy a Full-Stack Next.js App on Cloudflare Workers with GitHub Actions CI/CD How to Build a Multi-Tenant SaaS Platform with Next.js, Express, and Prisma How I Completed 15 freeCodeCamp Certifications in 4 Months: A Structured Learning Journey How to Build an Agentic Terminal Workflow with GitHub Copilot CLI and MCP Servers How AI Changed the Economics of Writing Clean Code How to Apply STRIDE Threat Modeling and SonarQube Analysis for Secure Software Development How to Set Up OpenID Connect (OIDC) in GitHub Actions for AWS How to Split PDF Files in the Browser Using JavaScript (Step-by-Step) How to Build Your Own Language-Specific LLM [Full Handbook] How to Build a Self-Learning RAG System with Knowledge Reflection How to Trace Multi-Agent AI Swarms with Jaeger v2 How I Tested Malaysia's Open Data Portals with Plain English How I Built a Production-Ready CI/CD Pipeline for a Monorepo-Based Microservices System with Jenkins, Docker Compose, and Traefik The Hidden Tax of Infrastructure: Why Your Team Shouldn’t Be Running It Anymore From Metrics to Meaning: How PaaS Helps Developers Understand Production From Symptoms to Root Cause: How to Use the 5 Whys Technique Product Experimentation for AI Rollouts: Why A/B Testing Breaks and How Difference-in-Differences in Python Fixes It How to Create a GPU-Optimized Machine Image with HashiCorp Packer on GCP 3D Web Development with Blender and Three.js How to Fix a Failing GitHub PR: Debugging CI, Lint Errors, and Build Errors Step by Step How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step) How to Handle Stripe Webhooks Reliably with Background Jobs How to Build an Automatic Knowledge Graph for Your Blog with PHP and JSON-LD Understanding Proxies and Reverse Proxies: Your Gateway to Secure Networking The Evolution of Nvidia Blackwell GPU Memory Architecture How to Use PostgreSQL as a Cache, Queue, and Search Engine The New Definition of Software Engineering in the Age of AI Reclaim Your Time – Master Automation with Zapier How to Create Dynamic Emails in Go with React Email Why Many Beginner Self-Taught Developers Struggle (And What to Do About It) How to Build a Headless WordPress Frontend with Astro SSR on Cloudflare Pages How to Make Your GitHub Profile Stand Out How to Use Context Hub (chub) to Build a Companion Relevance Engine Why Chrome OS Is the Operating System the AI Era Was Built For How to Build Microservices-Based REST APIs for Healthcare Portals How to friction-max your learning with software engineer Jessica Rose [Podcast #216] Shadow AI Explained: Why Employees Are Using AI Behind Your Back Traditional Scraping vs AI Scraping: A Practical Guide for Developers and Data Teams How Database Indexes Work – A Practical Guide with PostgreSQL Examples How to Streamline Search in Web Applications with Elasticsearch How to Build an Open Source Data Lake for Batch Ingestion OpenAI Codex Essentials – AI Assisted Agentic Development Course Learn Software System Design How to Generate PDF Files in the Browser Using JavaScript (With a Real Invoice Example) How to Get Started with Terraform Service-to-Service Communication: When to Use REST, gRPC, and Event-Driven Messaging A Developer’s Guide to Lazy Loading in React and Next.js The Data Quality Handbook: Data Errors, the Developer's Role, and Validation Layers Explained. United States Residential Proxy: Why Local IP Accuracy Matters for SERP, Ads, and Pricing How to Build a Fashion App That Helps You Organize Your Wardrobe How to Build an Admin Dashboard Sidebar with shadcn/ui and Base UI The AI Governance Handbook: How to Build Responsible AI Systems That Actually Ship How to Build a Local DevOps HomeLab with Docker, Kubernetes, and Ansible How to Use Mixins in Flutter [Full Handbook] How to Prep for Technical Interviews – A Guide for Web Developers GPT-5.4 vs GLM-5: Is Open Source Finally Matching Proprietary AI? Data Visualization Tools for Svelte Developers How to Keep Human Experts Visible in Your AI-Assisted Codebase Efficient Data Processing in Python: Batch vs Streaming Pipelines Explained How to Build and Deploy Multi-Architecture Docker Apps on Google Cloud Using ARM Nodes (Without QEMU) How to Build a Secure AI PR Reviewer with Claude, GitHub Actions, and JavaScript How to Build a Positioning-Based Crude Oil Strategy in Python [Full Handbook] How to learn programming and CS in the AI hype era – interview with dev and prof Mark Mahoney [Podcast #215] CUDA Programming for NVIDIA H100s How to Build Reliable AI Systems. How to Build an Online Marketplace with Next.js, Express, and Stripe Connect How to Build a Cost-Efficient AI Agent with Tiered Model Routing The WebCodecs Handbook: Native Video Processing in the Browser The Bluetooth LE Audio Handbook: From "Why Does My Call Sound Like a Tin Can?" to AOSP Implementation How to Set Up OpenClaw and Design an A2A Plugin Bridge
How to Build a Browser-Based PDF Watermark Tool Using JavaScript
Bhavin Sheth · 2026-05-19 · via freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
How to Build a Browser-Based PDF Watermark Tool Using JavaScript

PDF watermarks are commonly used for branding, document protection, approvals, confidential files, and internal document tracking.

Whether it’s adding a company logo, a “CONFIDENTIAL” label, or a draft watermark, users often need a quick way to modify PDFs without uploading files to external servers.

Modern browsers make this much easier than before. Instead of sending documents to a backend, we can process PDF files directly inside the browser using JavaScript. This keeps documents private while making the tool fast and easy to use.

In this tutorial, you’ll build a browser-based PDF watermark tool using JavaScript.

The tool will support both text and image watermarks, adjustable opacity, rotation, page selection, positioning controls, and downloadable PDF output directly from the browser.

Everything works entirely client-side without any backend.

Table of Contents

  1. How PDF Watermarking Works

  2. Project Setup

  3. What Library Are We Using?

  4. Creating the Upload Interface

  5. Adding Text Watermarks

  6. Adding Image Watermarks

  7. Positioning and Opacity Controls

  8. Selecting Pages to Apply

  9. Generating and Downloading the Final PDF

  10. Demo: How the PDF Watermark Tool Works

  11. Important Notes from Real-World Use

  12. Common Mistakes to Avoid

  13. Conclusion

How PDF Watermarking Works

A PDF watermark is simply additional text or an image layered on top of an existing PDF page.

In the browser, JavaScript libraries can load PDF pages, modify them visually, and export a new downloadable version.

The process starts when the user uploads a PDF file into the tool. JavaScript then reads the document, loads each page, and applies watermark elements like text or logos on top of the existing content. After positioning and opacity settings are applied, the updated PDF is generated and downloaded directly from the browser.

Everything happens locally inside the browser. This means uploaded documents never leave the user’s device, which improves privacy and security.

Project Setup

This project is intentionally simple. Everything runs directly inside the browser using JavaScript, so no backend server is required.

You only need:

  • an HTML file

  • a JavaScript file

  • a PDF processing library

What Library Are We Using?

We’ll use the PDF-lib library for editing existing PDF documents inside the browser.

Add it using a CDN:

<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>

This library allows us to load PDF files directly in the browser, modify existing pages, insert custom text or image watermarks, and finally export the updated document as a new downloadable PDF.

Because everything runs client-side with JavaScript, users can edit PDFs without uploading files to a server.

How to Create the Upload Interface

Start with a basic upload input:

<input type="file" id="pdfUpload" accept="application/pdf">

<button onclick="addWatermark()">
  Apply Watermark
</button>

This allows users to upload PDF files directly from the browser.

The tool also includes watermark settings like text input, image upload, opacity controls, positioning, and page selection.

Here’s what the watermark settings panel looks like inside the tool:

PDF watermark settings panel with text watermark controls and page selection options

How to Add Text Watermarks

Text watermarks are commonly used for labels like “CONFIDENTIAL”, “DRAFT”, or “APPROVED”.

For example:

page.drawText("CONFIDENTIAL", {
  x: 200,
  y: 300,
  size: 48,
  opacity: 0.5
});

This inserts watermark text directly onto the PDF page. Users can also customize the appearance of the watermark directly inside the tool.

For text watermarks, users can adjust the font size, change the text color, apply bold or italic styling, control opacity levels, and rotate the watermark at different angles for better visibility and protection.

Here’s an example of text watermark controls inside the tool:

Text watermark configuration options with font size color opacity and rotation controls

How to Add Image Watermarks

Some users may want to apply logos or branded graphics instead of plain text.

For example:

const image = await pdfDoc.embedPng(imageBytes);

page.drawImage(image, {
  x: 180,
  y: 250,
  width: 120,
  height: 120,
  opacity: 0.5
});

This inserts an image watermark onto the PDF page.

The tool also supports image scaling controls so users can resize uploaded logos before applying them.

Here’s an example of image watermark settings inside the tool:

Image watermark configuration panel with upload scale opacity and positioning controls

Positioning and Opacity Controls

Watermark placement is important for readability and document appearance.

Users may want centered watermarks, corner positioning, or diagonal overlays depending on the document type.

For example:

page.drawText("CONFIDENTIAL", {
  x: 220,
  y: 250,
  rotate: degrees(45),
  opacity: 0.5
});

This creates a rotated semi-transparent watermark.

The tool also allows users to adjust watermark positioning and appearance directly inside the browser.

Users can control the X and Y position, change opacity levels, rotate the watermark at different angles, and quickly move the watermark using directional placement controls.

This makes it easier to place watermarks correctly without manually editing the PDF in external software.

Here’s an example of positioning controls inside the tool:

PDF watermark positioning controls with opacity rotation and directional placement options

How to Select Pages to Apply

Not every watermark needs to appear on every page. Some users may only want watermarks on specific pages.

For example:

const selectedPages = [1, 3, 5];

The tool allows users to control exactly where the watermark should appear.

For example, a watermark can be applied to every page in the document, only even-numbered pages, only odd-numbered pages, or specific custom page ranges like 1-3,5.

This makes the tool more flexible for real-world use cases such as contracts, invoices, reports, certificates, and branded documents..

Here’s an example of page selection options inside the tool:

Page selection options for applying PDF watermarks to specific pages

How to Generate and Download the Final PDF

Once watermark settings are configured, the browser generates the updated PDF directly inside the browser.

For example:

const pdfBytes = await pdfDoc.save();

Then the updated file becomes downloadable:

download(pdfBytes, "watermarked.pdf");

This process happens locally without uploading files to external servers.

Demo: How the PDF Watermark Tool Works

For this example, we’ll apply a custom watermark directly inside the browser.

Step 1: Upload the PDF

Users upload a PDF document into the watermark tool.

allinonetools pdf tools hub pdf waternark pdf file uplaod

Step 2: Preview the Uploaded PDF

After uploading the PDF, the tool generates a live preview directly inside the browser.

Users can navigate through pages using the left and right arrow buttons to review the document before applying the watermark.

This page-by-page preview helps users verify the correct file, check page content, and decide where the watermark should appear.

Here’s how the PDF preview section looks inside the tool:

PDF watermark tool showing uploaded PDF preview with left and right page navigation arrows for browsing document pages.

Step 3: Configure Watermark Settings

Users can choose between text or image watermark mode.

For text watermarks, users can customize font size, color, opacity, and rotation.

Custom text watermark settings inside browser-based PDF watermark tool

For image watermarks, users can upload a logo and adjust image scale before applying it.

Image watermark upload and scaling controls inside PDF watermark tool

Step 4: Position and Apply the Watermark

Users can reposition the watermark visually before generating the final file.

PDF watermark positioning controls with opacity rotation and directional placement options

The tool also allows users to control where the watermark should be applied within the document. For example, the watermark can appear on all pages, only even-numbered pages, only odd-numbered pages, or specific custom page ranges.

Page selection options for applying PDF watermarks to specific pages

Opacity and rotation controls help improve visibility without blocking important document content.

This gives users more flexibility when watermarking contracts, invoices, reports, certificates, or branded PDFs.

Step 5: Generate the Watermarked PDF

Once the watermark settings are configured, users can click the generate button to process the document directly inside the browser.

The tool applies the watermark to the selected pages and prepares the updated PDF instantly.

Here’s how the generate PDF button looks inside the tool:

Generate PDF watermark button inside browser-based PDF watermark tool.

Step 6: Preview and Download the Updated PDF

After processing is complete, the tool displays a live preview of the final watermarked PDF.

Users can review the updated document before downloading it. The interface also shows useful file details such as total pages and final file size.

A rename option is available before downloading the generated PDF.

Here’s an example of the final output preview section:

Watermarked PDF preview with rename option, download button, total pages, and file size information.

Important Notes from Real-World Use

When working with large PDF documents, performance and rendering speed become important.

Applying watermarks page-by-page is usually more stable than modifying everything simultaneously.

For example:

for (const page of pdfDoc.getPages()) {
  // apply watermark
}

Another useful optimization is lowering image watermark size before embedding large logos. This reduces output file size and improves processing speed.

Opacity is also important. Very dark watermarks can make documents difficult to read, especially on printed pages. Keeping watermark opacity between 0.3 and 0.5 usually works well in real-world situations.

Since everything runs locally inside the browser, uploaded documents remain private and never leave the user’s device.

Common Mistakes to Avoid

One common mistake is applying watermarks at full opacity. This can make the document difficult to read.

For example:

opacity: 1

Instead, use lower opacity values:

opacity: 0.4

Another issue is incorrect watermark positioning. If coordinates are hardcoded incorrectly, the watermark may appear outside the visible page area.

Dynamic positioning usually works better across different page sizes. Large image watermarks can also increase PDF file size significantly. Resizing images before embedding them helps improve performance.

Another common mistake is forgetting to validate uploaded files:

if (!file || file.type !== "application/pdf") {
  alert("Please upload a valid PDF file.");
  return;
}

This prevents unsupported files from breaking the tool.

Conclusion

In this tutorial, you built a browser-based PDF watermark tool using JavaScript.

You learned how to upload PDF files, apply text or image watermarks, control positioning and opacity, and generate downloadable PDFs directly inside the browser.

More importantly, you saw how modern browsers can handle document editing tasks locally without relying on a backend server.

This approach keeps the tool fast, private, and easy to use.

You can also try the live tool here: All In One Tools PDF Watermark Tool

Once you understand this workflow, you can extend it further with features like digital signatures, PDF annotations, stamping tools, password protection, or advanced document editing.

And that’s where things start getting really interesting.



Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started