通过pdfjs-dist讲pdf转为图片进行预览的方式
存在失真的问题
npm i pdfjs-dist -S
<template>
<el-dialog :title="title" :visible.sync="dialogVisible" width="60%" :before-close="handleClose" append-to-body>
<canvas ref="canvas" v-if="reFresh"></canvas>
<span v-else>暂无数据</span>
<span slot="footer" class="dialog-footer">
<span class="jumpBtn">
<span style="margin-right:10px">共{{max_pageNum}}页</span>
前往
<el-input v-model="jumpNum" v-if="fileURL" @change="Page(2)"></el-input>页
</span>
<el-button @click="Page(0)" v-if="fileURL">上一页</el-button>
<el-button @click="Page(1)" v-if="fileURL">下一页</el-button>
<el-button @click="dialogVisible = false">关 闭</el-button>
</span>
</el-dialog>
</template>
<script>
import pdfJs from "pdfjs-dist";
import pdfjsLib from "pdfjs-dist/build/pdf.worker";
export default {
props: {
title: {
type: String,
default: '在线预览'
},
},
data() {
return {
imgUrl: '',
pageNum: 1,
max_pageNum: 0,
dialogVisible: false,
fileURL: '',
reFresh: true
}
},
watch: {
fileURL() {
this.reFresh = false
this.$nextTick(() => {
this.reFresh = true
})
}
},
methods: {
init(){
this.dialogVisible=true;
},
handleClose() {
this.dialogVisible = false
this.$emit('close')
},
handleOpen(val) {
this.dialogVisible = true
this.fileURL = val
this.showPdf(1)
},
Page(val) {
if (val == 0) {
this.pageNum > 1 ? this.showPdf(this.pageNum - 1) : "";
} else if (val == 1) {
this.pageNum < this.max_pageNum
? this.showPdf(this.pageNum + 1)
: this.$message({ type: "warning", message: "已经是最一页" });
} else {
this.jumpNum <= this.max_pageNum && this.jumpNum > 0
? this.showPdf(this.jumpNum)
: this.$message({ type: "warning", message: "不存在该页" });
}
},
showPdf(num) {
let _this = this;
let imgArr = [];
pdfJs.workerSrc = 'pdf.worker.js';
let loadingTask = pdfJs.getDocument(this.fileURL);
loadingTask.promise.then(function (pdf) {
_this.max_pageNum = pdf.numPages;
_this.pageNum = num
pdf.getPage(Number(num)).then(function (page) {
let viewport = page.getViewport(2.0);
let canvas = _this.$refs.canvas
let context = canvas.getContext('2d');
canvas.height = viewport.height
canvas.width = viewport.width
let renderContext = {
canvasContext: context, viewport: viewport
};
let renderTask = page.render(renderContext);
context.clearRect(0, 0, canvas.width, canvas.height);
renderTask.then(function () {
canvas.toDataURL('image/jpeg'); //转换为base64
});
});
}, function (reason) {
console.error(reason);
});
function isEmpty(arr) {
for (let i = 0; i < arr.length; i++) {
if (!arr[i])
return true;
}
return false;
}
}
}
}
</script>
<style lang="scss" scoped>
>>> .el-dialog__body {
text-align: center;
}
.jumpBtn {
>>> .el-input{
width: 60px;
}
}
</style> >
使用
// 引入组件
import showPdf from '@/components/pdfView/index.vue'
//注册
components: { showPdf}
<showPdf ref="showPdf"></showPdf>
// 打开预览,传入pdf的完整路径
this.$refs.showPdf.handleOpen(this.applyURL)