Skip to main content

前端水印

编写工具类

最简单的方式就是通过canvas生成文字,然后转成base64,最后丢到宿主容器的背景中

export default class Watermark {
/**
* 设置水印
* @param str 水印文字
* @param parentNodeId 父节点id
* @param contentWindow iframe的window对象
* @param textWidth 文本区域宽度
* @param textHeight 文本区域高度
* @returns 水印dom的id
*/
setWatermark(str: string, parentNodeId: string, contentWindow?: Window, textWidth: number = 140, textHeight: number = 140) {
let parentNode = null;
let canvas = null;
if (contentWindow) {
parentNode = contentWindow.document.getElementById(parentNodeId) as HTMLElement;
canvas = contentWindow.document.createElement('canvas') as HTMLCanvasElement;
} else {
parentNode = document.getElementById(parentNodeId) as HTMLElement;
canvas = document.createElement('canvas') as HTMLCanvasElement;
}
canvas.width = textWidth;
canvas.height = textHeight;
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.rotate((Math.PI / 120) * -20);
ctx.font = "16px Microsoft Yahei";
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(str, textWidth / 10, textHeight / 1.5);
}
parentNode.style.position = 'relative';
parentNode.style.background = 'url(' + canvas.toDataURL('image/png') + ') left top repeat';
}

/**
* 设置页眉页脚为空,已无效
*/
setHeader() {
// 添加一个间距
let style = document.createElement('style')
style.innerHTML = "@page{size: a4;margin:" + '10mm' + "}"
window.document.head.appendChild(style);
//设置页眉页脚为空
let hkey_root, hkey_path, hkey_key;
hkey_root = "HKEY_CURRENT_USER";
hkey_path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
// let RegWsh = new ActiveXObject("WScript.Shell");
// hkey_key = "header";
// RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "");
// hkey_key = "footer";
// RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "");
}
/**
* 删除水印结点
* @param id 水印id
* @param parentNodeId 水印父容器id
*/
removeWatermark(parentNodeId: string, contentWindow?: Window) {
let parentNode = null;
if (contentWindow) {
parentNode = contentWindow.document.getElementById(parentNodeId) as HTMLElement;
} else {
parentNode = document.getElementById(parentNodeId) as HTMLElement;
}
parentNode.style.background = 'unset';
}
}

使用

const watermark = new Watermark();
watermark.setWatermark('测试水印', 'printid');
watermark.removeWatermark('printid');