vue pdf预览
用到的插件是vuepdf
1、对于不能通过npm install安装的,需要去官网下载打包好的文件,文件夹大概是这个样子的,
然后在用到的.vue文件中引入就ok了
创建一个展示pdf的容器 <div id="mycanvas" ref="mycanvas"></div>
引入import pdf from '../../../lib/pdf/build/pdf'
创建一个解析pdf的方法,如果后台返回pdf的base64,
async showBase64Pdf() {
let base64 = this.pdfDataList
let pdfjsLib = pdf
pdfjsLib.PDFJS.workerSrc = AppConst.STATIC_FILE + '/lib/pdf/build/pdf.worker.js' //这里根据自己项目路径引入
let decodedBase64 = window.atob(base64) //使用浏览器自带的方法解码
let pdf12 = await pdfjsLib.getDocument({ data: decodedBase64 }) //返回一个pdf对象
let pages = pdf12.numPages //声明一个pages变量等于当前pdf文件的页数
for (let i = 1; i <= pages; i++) { //循环页数
let container = document.getElementById('mycanvas')
let canvas = document.createElement('canvas')
let page = await pdf12.getPage(i) //调用getPage方法传入当前循环的页数,返回一个page对象
let scale = (container.offsetWidth / page.view[2]); //缩放倍数,1表示原始大小
let viewport = page.getViewport(scale);
let context = canvas.getContext('2d'); //创建绘制canvas的对象
canvas.height = viewport.height; //定义canvas高和宽
canvas.width = viewport.width;
let renderContext = {
canvasContext: context,
viewport: viewport
};
await page.render(renderContext)
canvas.className = 'canvas' //给canvas节点定义一个class名,这里我取名为canvas
container.appendChild(canvas) //插入到pdfList节点的最后
}
},
如果后台返回一个pdfURL
async showURLPdf() {
let base64 = this.pdfDataList
let pdfjsLib = pdf
pdfjsLib.PDFJS.workerSrc = AppConst.STATIC_FILE + '/lib/pdf/build/pdf.worker.js' //这里根据自己项目路径引入
let pdf12 = await pdfjsLib.getDocument(url) //这里也可以接收一个pdf文件的链接
let pages = pdf12.numPages //声明一个pages变量等于当前pdf文件的页数
for (let i = 1; i <= pages; i++) { //循环页数
let container = document.getElementById('mycanvas')
let canvas = document.createElement('canvas')
let page = await pdf12.getPage(i) //调用getPage方法传入当前循环的页数,返回一个page对象
let scale = (container.offsetWidth / page.view[2]); //缩放倍数,1表示原始大小
let viewport = page.getViewport(scale);
let context = canvas.getContext('2d'); //创建绘制canvas的对象
canvas.height = viewport.height; //定义canvas高和宽
canvas.width = viewport.width;
let renderContext = {
canvasContext: context,
viewport: viewport
};
await page.render(renderContext)
canvas.className = 'canvas' //给canvas节点定义一个class名,这里我取名为canvas
container.appendChild(canvas) //插入到pdfList节点的最后
}
},
1、对于能通过npm install安装的,就很简单
安装好后,在需要预览pdf的页面引入
import pdf from 'vue-pdf'
创建组件
<pdf v-for="item in numPages" :key="item" :src="pdfsrc" :page="item" />
加载pdf的方法
loadPdf(url) {
this.pdfsrc = pdf.createLoadingTask(url)
this.pdfsrc.promise.then((pdf) => {
this.numPages = pdf.numPages // 这里拿到当前pdf总页数
})
},