vue项目展示pdf文件的方法实现
作者:Miss Stone
本文主要介绍了vue项目展示pdf文件的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
最近我有个需求,就是在h5页面上展示pdf文件,分页,最后一页有个蒙层阴影渐变的效果,尝试过一些插件,但都不是很好用,最后用了pdfjs-dist加上canvas 可以看下效果
先下载:
npm i pdfjs-dist@2.5.207
下面展示代码 html:
<template> <canvas v-for="pageNumber in pageCount" :key="pageNumber" :id="`refCanvas${pageNumber}`" style="width: 100%; height: auto"></canvas> </template>
js:
<script> import workerSrc from 'pdfjs-dist/build/pdf.worker.entry' const PDFJS = require('pdfjs-dist') PDFJS.workerSrc = workerSrc export default { data() { return { url: '', pageCount: null, scale: 2, width: '', height: '', } }, mounted() { this.getPdfFile() }, methods: { async getPdfFile() { await apiName({ xxx:xxx }).then((res) => { var binaryData = []; binaryData.push(res); let url = window.URL.createObjectURL(new Blob(binaryData, { type: "application/pdf" })) this.url = url this._loadFile(url); }).catch((err) => { console.log('err', err) }) }, _loadFile (url) { // 获取整个 文档 PDFJS.getDocument({ url, cMapPacked: true }).promise.then(async (pdf) => { let pageCount = pdf.numPages this.pageCount = pageCount for (let i = 1; i <= pageCount; i++) { const page = await pdf.getPage(i) const viewport = page.getViewport({scale: this.scale}) const canvas = document.getElementById(`refCanvas${i}`); canvas.height = viewport.height canvas.width = viewport.width this.width = viewport.width this.height = viewport.height const renderContext = { canvasContext: canvas.getContext('2d'), viewport } page.render(renderContext).promise.then(() => { // 最后一页pdf增加蒙层 if(i === pageCount) { this.addMask(i) } }) } },(err) => { if(err.name == 'MissingPDFException'){ console.log('无效的PDF链接') } }) }, // 添加蒙层 addMask(i) { const canvas = document.getElementById(`refCanvas${i}`); let ctx = canvas.getContext('2d') const gradient = ctx.createLinearGradient(0, this.height / 5, 0, this.height); gradient.addColorStop(0, "rgba(243, 244, 249, 0)"); gradient.addColorStop(0.2, "rgba(243, 244, 249, 0.3)"); gradient.addColorStop(0.4, "rgba(243, 244, 249, 0.7)"); gradient.addColorStop(0.5, "rgba(243, 244, 249, 0.9)"); gradient.addColorStop(0.6, "rgba(243, 244, 249, 1)"); gradient.addColorStop(0.8, "rgba(243, 244, 249, 1)"); gradient.addColorStop(1, "rgba(243, 244, 249, 1)"); ctx.fillStyle = gradient; ctx.fillRect (0, this.height / 5, this.width, (this.height / 5) * 4); } } } </script>
到此这篇关于vue项目展示pdf文件的方法实现的文章就介绍到这了,更多相关vue展示pdf文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!