一、使用插件pdfh5预览pdf
参考文档:pdfh5 - npm
使用pdfh5在线预览pdf并且加上文字水印
①安装插件:npm install pdfh5
②使用pdfh5插件预览pdf
<template>
<div class="m-pdf">
<div class="pdfImg"></div>
</div>
</template>
<script>
import pdfjs from 'pdfh5/js/pdf';
import pdfWorker from 'pdfh5/js/pdf.worker';
pdfjs.GlobalWorkerOptions.workerSrc = pdfWorker;
export default {
name: 'Pdfh5',
data() {
return {
pdfh5: null,
fileUrl: '' // 如果引入本地pdf文件,需要将pdf放在public文件夹下,引用时使用绝对路径(/:表示public文件夹)
};
},
mounted() {
this.fileUrl = decodeURIComponent(this.$route.query.fileUrl);
this.pdfInit(this.fileUrl);
/* // pdfh5实例化时传两个参数:selector选择器,options配置项参数,会返回一个pdfh5实例对象,可以用来操作pdf,监听相关事件
this.pdfh5 = new Pdfh5('#pdf', {
pdfurl: this.fileUrl, // pdf 地址,请求的地址需要为线上的地址,测试的本地的地址是不可以的
withCredentials: true,
renderType: 'canvas',
maxZoom: 3, //手势缩放最大倍数 默认3
scrollEnable: true, //是否允许pdf滚动
zoomEnable: true //是否允许pdf手势缩放
});
// 监听pdf准备开始渲染,此时可以拿到pdf总页数
this.pdfh5.on('ready', function () {});
// 监听pdf加载完成事件,加载失败、渲染成功都会触发
this.pdfh5.on('complete', (status, msg, time) => {
console.log('状态:' + status + ',信息:' + msg + ',耗时:' + time + '毫秒');
}); */
},
methods: {
async pdfInit(pdfUrl) {
try {
const pdfDoc = await pdfjs.getDocument(pdfUrl).promise;
const totalPage = pdfDoc.numPages;
for (let i = 1; i <= totalPage; i++) {
const page = await pdfDoc.getPage(i);
let scaledViewport = page.getViewport({ scale: 1.5 });
let canvas = document.createElement('canvas');
canvas.height = scaledViewport.height;
canvas.width = scaledViewport.width;
const listIndex = +document.querySelector('.pdfImg').childNodes.length;
canvas.className = 'img-item';
canvas.setAttribute('data-pdf-index', listIndex);
canvas.style.width = '100%';
let context = canvas.getContext('2d');
let renderContext = {
canvasContext: context,
viewport: scaledViewport
};
await page.render(renderContext);
// 这个方法是加水印的
const canvasFillStyle = context.createPattern(this.initWatermark(), 'repeat');
context.rect(0, 0, scaledViewport.width, scaledViewport.height);
context.fillStyle = canvasFillStyle;
context.fill();
canvas.remove();
document.querySelector('.pdfImg').appendChild(canvas);
}
return [];
} catch (error) {
return error;
}
},
initWatermark() {
let canvas = document.createElement('canvas');
canvas.width = 460;
canvas.height = 240;
let ctx = canvas.getContext('2d');
ctx.font = '36px Vedana';
ctx.fillStyle = 'rgba(200, 200, 200, 0.4)';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.rotate((-18 * Math.PI) / 80);
ctx.fillText('水印水印水印水印水印', 0, 260);
return canvas;
}
}
};
</script>
<style lang="less" scoped>
.m-pdf {
// 保证pdf区域铺满整个屏幕
// 方法1:使用vw和vh视窗单位,1vw=视窗宽度的1%;1vh=视窗高度的1%
// width: 100vw;
// height: 100vh;
// 方法2:使用fixed定位
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
.header-bg {
background: #fff;
.title {
margin: auto;
padding: 10px 0px 0px 0px;
font-weight: 600;
font-size: 40rpx;
font-family: PingFangHK-Semibold, PingFangHK;
font-weight: 600;
color: #333333;
line-height: 56rpx;
}
}
}
</style>