PDF.JS如何禁止下载、打印并添加自定义水印

1. 下载并引入PDF.js实现预览

官网下载地址:https://mozilla.github.io/pdf.js,下载完成后将压缩包解压;

2.如何动态加载PDF文件,在head添加变量。如下以PHP为例

<script>
		var productFilePath = 'file=<?php echo $PDFUrf; ?>';//后台Action传入前台的pdf文件路径参数赋值给url
		// console.log(productFilePath);
</script>

然后在viewer.js中找到function webViewerInitialized

var queryString = document.location.search.substring(1);//修改这行的内容
var queryString = productFilePath;
动态加载PDF文件
修改 webViewerInitialized 方法

3、如何禁止下载、打印

3.1、先隐藏起button按钮。在viewer.html文件中,搜索“ openFile、print、download ”,添加类 visibleMediumView 。备注:在viewer.css中,. visibleMediumView 在某些响应式布局中,需要重新设置display:none;

3.2虽然上面已经对按钮隐藏了,但是快捷键依然生效。屏蔽快捷键打印

打开viewer.js

屏蔽window.print();
禁止快捷键打印
屏蔽window.print();

4、添加动态水印

首先在head中添加变量。如var watermark = “星伴同行”;

if (this.textLayerMode !== _ui_utils.TextLayerMode.DISABLE && this.textLayerFactory) {
var textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height;
//---这里就是要插入水印的位置---
if (this.annotationLayer && this.annotationLayer.div) {
div.insertBefore(textLayerDiv, this.annotationLayer.div);
//此处需要添加appendchild,参照下面代码框
} else {
div.appendChild(textLayerDiv);
//此处需要添加appendchild,参照下面代码框
}
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.textLayerMode === _ui_utils.TextLayerMode.ENABLE_ENHANCE);
//此处添加一个for循环,具体参数下面第二个代码框
}
 if (this.annotationLayer && this.annotationLayer.div) {
        div.insertBefore(canvasWrapper, this.annotationLayer.div);
		div.appendChild(cover);	//水印添加
      } else {
        div.appendChild(canvasWrapper);
		div.appendChild(cover);//水印添加
      }
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.textLayerMode === _ui_utils.TextLayerMode.ENABLE_ENHANCE);
		var cover = document.getElementsByClassName('cover');
		for (var i = 0, len = cover.length; i < len; i++) {
			cover[i].style.width = canvasWrapper.style.width;
			cover[i].style.height = canvasWrapper.style.height;
		}

最后修改 viewer.css

关于Thinkphp下加载pdf.js,出现pdf.work.js not found问题解决办法

打开viewer.js。找到代码并修改正确路径

 pdf.work.js not found
pdf.work.js not found

修改后保存,仍会抛出错误compressed.tracemonkey-pldi-09.pdf is not found

compressed.tracemonkey-pldi-09.pdf is not found
compressed.tracemonkey-pldi-09.pdf is not found