今日已更新 501 条资讯 | 累计 23137 条内容
关于我们

How to Add Watermarks to PDFs in the Browser with Vue 3 and pdf-lib

sunshey 2026年07月23日 20:40 0 次阅读 来源:Dev.to

Watermarking a PDF — adding semi-transparent text over pages — sounds like something only desktop software handles. But with pdf-lib and a bit of canvas math, you can build a fully browser-based watermark tool. This post walks through the implementation details, including text rendering, rotation, and multi-page support. Why client-side? Traditional watermark tools upload your file, process it on a server, and send the result back. For documents that might be confidential or contain sensitive information, this introduces an unnecessary privacy risk. A browser-based approach: Processes everything locally Keeps files on the user's device Works offline after loading Avoids server-side bandwidth costs The stack Vue 3 + Composition API pdf-lib for PDF manipulation and watermarks PDF.js ( pdfjs-dist ) for preview rendering Vite for bundling Adding a text watermark pdf-lib provides a built-in PDFDocument.embedFont() method for custom fonts and page.drawText() for placing text. Here's how to add a rotated, semi-transparent watermark across all pages: < script setup lang= "ts" > import { ref } from ' vue ' import { PDFDocument , rgb , StandardFonts } from ' pdf-lib ' const file = ref < File | null > ( null ) const watermarkText = ref ( ' DRAFT ' ) const opacity = ref ( 0.3 ) const fontSize = ref ( 72 ) const rotationDeg = ref ( - 45 ) const applying = ref ( false ) async function handleFileUpload ( selected : File ) { file . value = selected } async function applyWatermark () { if ( ! file . value ) return applying . value = true try { const arrayBuffer = await file . value . arrayBuffer () const pdfDoc = await PDFDocument . load ( arrayBuffer ) // Embed the Helvetica font — required for correct rendering const helveticaFont = await pdfDoc . embedFont ( StandardFonts . HelveticaBold ) const pages = pdfDoc . getPages () pages . forEach (( page ) => { const { width , height } = page . getSize () page . drawText ( watermarkText . value , { x : ( width - helveticaFont . widthOfT

本文内容来源于互联网,版权归原作者所有
查看原文