提示:
1、不兼容IE及兼容模式下的360浏览器(极速模式可以兼容),以上浏览器请自行为用户设置不兼容提醒
2、canvas画布是浮动在页面元素之上的,请知悉
3、这里pdf文件由后端接口返回,如:http://192.168.1.164/imgs/202004/1588144455734.pdf
4、若pdf渲染不出来,则考虑是否是因为pdf文件地址的跨域问题
效果图
实现步骤
1、安装pdfjs依赖
yarn add pdfjs-dist 或 npm install pdfjs-dist --save
2、在页面某个位置使用canvas画布来渲染pdf文件
3、data里注册pages
data(){
pages:'', //pdf分页
}
4、引入PDFJS ,并调用相关函数_renderPage(),_loadFile()
import PDFJS from 'pdfjs-dist'
methods:{
_renderPage (num) {
this.pdfDoc.getPage(num).then((page) => {
let canvas = document.getElementById('the-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
let ratio = dpr / bsr
let viewport = page.getViewport(screen.availWidth / page.getViewport(1).width)
canvas.width = viewport.width * ratio
canvas.height = viewport.height * ratio
// canvas.style.width = viewport.width + 'px'
canvas.style.width = 7 + 'rem'
// canvas.style.height = viewport.height + 'px'
ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
let renderContext = {
canvasContext: ctx,
viewport: viewport
}
page.render(renderContext)
if (this.pages > num) {
this._renderPage(num + 1)
}
})
},
_loadFile (url) {
PDFJS.getDocument(url).then((pdf) => {
this.pdfDoc = pdf
this.pages = this.pdfDoc.numPages
this.$nextTick(() => {
this._renderPage(1)
})
})
},
}
5、调用函数传入pdf文件地址进行渲染
this._loadFile(pdfurl)