1、下载依赖
javascript
npm install pdfjs-dist@2.2.228
2、在需要用的页面引入
javascript
<script>
import * as PDFJS from 'pdfjs-dist';
export default{
data(){
return{
}
},
created(){
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.min.js')
},
mounted(){
this.hanle()
}
}
</script>
3、其它都在methods
javascript
//pdf 创建画布
createPdfContainer(id,className) {
var pdfContainer = document.getElementById('pdf-container');
var canvasNew =document.createElement('canvas');
canvasNew.id = id;
canvasNew.className = className;
pdfContainer.appendChild(canvasNew);
this.loadings = false
},
// 渲染pdf 给pdf定宽度
renderPDF(pdf,i,id) {
pdf.getPage(i).then(function(page) {
var scale = 1.67;
var viewport = page.getViewport(scale);
//
// 准备用于渲染的 canvas 元素
//
var canvas = document.getElementById(id);
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//
// 将 PDF 页面渲染到 canvas 上下文中
//
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
},
//创建和pdf页数等同的canvas数
createSeriesCanvas(num,template) {
const _this = this
var id = '';
for(var j = 1; j <= num; j++){
id = template + j;
_this.createPdfContainer(id,'pdfClass');
}
},
hanle() {
const _this= this
_this.loadings = true
//如果pdf加密了 就用下面的obj
let obj = {
url:_this.dataurl,
password:'你的密码'
}
//如果pdf没有加密 就路径就好
let obj = {
url:_this.dataurl
}
PDFJS.getDocument(obj).then(function(pdf) {
//用 promise 获取页面
var id = '';
var idTemplate = 'cw-pdf-';
var pageNum = pdf.numPages;
//根据页码创建画布
_this.createSeriesCanvas(pageNum,idTemplate);
//将pdf渲染到画布上去
for (var i = 1; i <= pageNum; i++) {
id = idTemplate + i;
_this.renderPDF(pdf,i,id);
}
});
},
4、页面
javascript
<div class="left" ref="content">
<div ref="pdfViewer" id="pdf-container" class="pdfView" v-loading="loadings"></div>
</div>