1.原生方法
<div>
<div class="bottom" style="position: fixed;right: 0">
<input class="pdf-zoom" type="submit" value="+" @click="zoomPdf(1)"/>
</br>
<input class="pdf-zoom" type="submit" value="-" @click="zoomPdf(0)"/>
</div>
<div id="canvasEle"></div>
</div>
pdfContent: {
canvasEle: '', // 渲染pdf的元素
detail: '', // pdf详情
scale: 1 // 放缩比例
},
this.pdfContent['canvasEle'] = document.getElementById("canvasEle");
this.pdfContent['detail'] = res.data;
this.loadPdf(this.pdfContent, 0);
/**
* pdf放大/缩小
*/
zoomPdf(num) {
const pObjs = this.pdfContent.canvasEle.childNodes;
for (let i = pObjs.length - 1; i >= 0; i--) { // 一定要倒序,正序是删不干净的,可自行尝试
this.pdfContent.canvasEle.removeChild(pObjs[i]);
}
if (num) {
this.pdfContent.scale = this.pdfContent.scale + 0.5;
} else {
this.pdfContent.scale > 1 ? this.pdfContent.scale = this.pdfContent.scale - 0.5 : ''
}
this.loadPdf(this.pdfContent);
},
/**
* 加载pdf
*/
async loadPdf(pdfContent, flag){
const pdfData = atob(pdfContent.detail)
pdfjsLib.GlobalWorkerOptions.workerSrc ='https://cdn.jsdelivr.net/npm/pdfjs-dist@2.4.456/build/pdf.worker.js';
const loadingTask = pdfjsLib.getDocument({ data: pdfData, });
const pdf = await loadingTask.promise;
for (let i = 1; i < pdf.numPages + 1; i++) {
const page = await pdf.getPage(i);
let viewport = page.getViewport({ scale: pdfContent.scale });
this.proportion = this.clientWidth / viewport.width;
if (flag === 0) {
this.pdfContent.scale = this.pdfContent.scale * this.proportion;
viewport = page.getViewport({ scale: pdfContent.scale });
}
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport,
};
pdfContent.canvasEle.appendChild(canvas);
page.render(renderContext);
}
}
2.使用vue-pdf
(1)安装
npm install --save vue-pdf
(2)基本使用
<template>
<div class="pdf">
<pdf
ref="pdf"
:src="pdfUrl">
</pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
name: 'Pdf',
components:{
pdf
},
data(){
return {
pdfUrl:"http://file.dakawengu.com/file/2018-05-29/20180527-tianfeng.pdf",
}
}
</script>