记录贴
最近我有个需求,就是在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>