', '文件已加载'); }); function escapeHtml(s) { return String(s).replace(/[&<>"']/g, function(c) { return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]; }); } function render() { if (!currentFile) { showError('请先选 PDF'); return; } var text = getVal('text-a') || '水印'; var fs = parseInt($('font-size').value, 10); var opacity = parseFloat($('opacity').value); var angle = parseInt($('angle').value, 10); var pos = getVal('position'); var color = $('color').value; var pages = getVal('pages'); // 简化:用 Canvas 模拟 1 页 PDF 预览(595×842 = A4 @ 72dpi) var W = 595, H = 842; var canvas = document.createElement('canvas'); canvas.width = W; canvas.height = H; var ctx = canvas.getContext('2d'); // 背景 ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, W, H); // 模拟 PDF 文本(几条横线) ctx.fillStyle = '#e5e7eb'; for (var y = 80; y < H - 60; y += 25) { ctx.fillRect(60, y, W - 120, 8); } ctx.fillStyle = '#222'; ctx.font = 'bold 14px sans-serif'; ctx.fillText('PDF 预览 (' + currentFile.name + ')', 60, 40); // 水印 ctx.save(); ctx.globalAlpha = opacity; ctx.fillStyle = color; ctx.font = 'bold ' + fs + 'px sans-serif'; ctx.textBaseline = 'middle'; if (pos === 'tile') { // 平铺:每 200 像素一个 for (var ty = 100; ty < H; ty += Math.max(120, fs + 60)) { for (var tx = 50; tx < W; tx += Math.max(200, text.length * fs / 1.5 + 80)) { ctx.save(); ctx.translate(tx, ty); ctx.rotate(angle * Math.PI / 180); ctx.textAlign = 'center'; ctx.fillText(text, 0, 0); ctx.restore(); } } } else { var cx = W / 2, cy = H / 2; if (pos === 'top-left') { cx = 150; cy = 80; } else if (pos === 'top-right') { cx = W - 150; cy = 80; } else if (pos === 'bottom-left') { cx = 150; cy = H - 80; } else if (pos === 'bottom-right') { cx = W - 150; cy = H - 80; } ctx.translate(cx, cy); ctx.rotate(angle * Math.PI / 180); ctx.textAlign = 'center'; ctx.fillText(text, 0, 0); } ctx.restore(); var dataUrl = canvas.toDataURL('image/png'); var pageLabel = pages === 'all' ? '所有页(预览首页)' : pages === 'first' ? '仅第一页' : '仅最后一页'; showResult( '

预览(文字水印示例, ' + pageLabel + '):

' + '
' + '说明:本工具在 Canvas 上生成水印预览,展示最终视觉效果。如需直接生成带水印的 PDF 文件,推荐使用 pdf-lib (服务端) 或客户端 pdf-lib.min.js(不在 clawam 静态库中)。' + '
', '文字 "' + text + '", ' + fs + 'px, 透明度 ' + opacity + ', 角度 ' + angle + '°' ); } $('btn-render').addEventListener('click', render); $('btn-download').addEventListener('click', function() { if (!currentFile) { showError('请先选 PDF'); return; } // 下载预览图为 PNG var img = document.querySelector('#result-content img'); if (!img) { showError('请先生成预览'); return; } var a = document.createElement('a'); a.href = img.src; a.download = 'watermark-preview.png'; a.click(); }); $('btn-clear').addEventListener('click', function() { $('file').value = ''; currentFile = null; var ra = $('result-area'); ra.hidden = true; ra.style.display = 'none'; var em = $('error-msg'); em.hidden = true; em.style.display = 'none'; }); })();