<template>
<div class="pdf-container" @contextmenu="showMenu">
<canvas v-for="page in pages" :id="'canvas' + page" :key="page"></canvas>
<vue-context-menu :contextMenuData="contextMenuData"
@savedata="savedata"
@newdata="newdata"></vue-context-menu>
</div>
</template>
<script>
import PDF from 'pdfjs-dist'
PDF.disableWorker = true
export default {
name: '',
data () {
return {
width: 100,
pdfDoc: null,
pages: 0,
// contextmenu data (菜单数据)
contextMenuData: {
// the contextmenu name(@1.4.1 updated)
menuName: 'demo',
// The coordinates of the display(菜单显示的位置)
axis: {
x: null,
y: null
},
// Menu options (菜单选项)
menulists: [{
fnHandler: 'savedata', // Binding events(绑定事件)
icoName: 'fa fa-home fa-fw', // icon (icon图标 )
btnName: 'Save' // The name of the menu option (菜单名称)
}, {
fnHandler: 'newdata',
icoName: 'fa fa-home fa-fw',
btnName: 'New'
}]
}
}
},
created(){
this.loadFile('/aa.pdf')
},
methods: {
showMenu () {
event.preventDefault()
var x = event.clientX
var y = event.clientY
// Get the current location
this.contextMenuData.axis = {
x, y
}
},
savedata () {
alert(1)
},
newdata () {
console.log('newdata!')
},
/*
* 加载PDF文件
* url:后台提供的pdf地址或者项目中public/pdf文件(test.pdf)
* 在需要的位置调用 this.loadFile(url)
* */
loadFile (url) {
PDF.getDocument(url)
.then((pdf) => {
this.pdfDoc = pdf
this.pages = this.pdfDoc.numPages
this.$nextTick(() => {
this.renderPage(1)
})
})
},
/*
* 渲染PDF文件
* */
renderPage (num) {
this.pdfDoc.getPage(num)
.then((page) => {
let canvas = document.getElementById('canvas' + num)
let ctx = canvas.getContext('2d')
let dpr = window.devicePixelRatio || 1 // 设备像素比
let bsr = ctxå.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1 // 浏览器在渲染canvas之前会用几个像素来来存储画布信息,类似img
let ratio = dpr / bsr
let viewport = page.getViewport(2.5)
canvas.width = viewport.width * ratio // 画布大小,默认值是width:300px,height:150px
canvas.height = viewport.height * ratio
canvas.style.width = viewport.width + 'px' // 画布的框架大小
canvas.style.height = viewport.height + 'px'
let renderContext = {
canvasContext: ctx,
viewport: viewport
}
page.render(renderContext)
if (this.pages > num) {
this.renderPage(num + 1)
} else {
// this.closeServerLoadingHandle()
}
})
}
}
}
</script>
<style>
.pdf-container{
width: 100%;
height: 100%;
position: absolute;
top:0;
left:0;
bottom:0;
right:0;
}
.vue-contextmenu-listWrapper{
padding: 0;
}
</style>