pdf展示有几张方式,一个是套iframe,一个就是用pdf.js。但是要注意的是pdf.js不能使用电子签章,如果需要使用电子签章的话需要注释原js里的几段代码,我这边直接使用了公司内部的https://www.npmjs.com/package/pdfjs-dist-with-digtal-signature-ke
项目是跑在vue里的,template、js如下
<canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"></canvas>
import PDFJS from 'pdfjs-dist-with-digtal-signature-ke'
// 渲染pdf流 这里后端返回的pdf_content是base64的流,atob是解码
this._loadFile(atob(res.data.pdf_content))
_loadFile(url) {
PDFJS.getDocument({ data: url }).then((pdf) => {
this.pdfDoc = pdf
this.pages = this.pdfDoc.numPages
this.$nextTick(() => {
this._renderPage(1)
})
})
},
_renderPage(num) {
this.pdfDoc.getPage(num).then((page) => {
const canvas = document.getElementById(`the-canvas${num}`)
const ctx = canvas.getContext('2d')
const dpr = window.devicePixelRatio || 1
const bsr = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1
const ratio = dpr / bsr
const 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.height = `${viewport.height}px`
ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
const renderContext = {
canvasContext: ctx,
viewport,
}
page.render(renderContext)
// pdf渲染出来之后进行页面展示加倒计时
this.showPage = true
const _this = this
this.interval = setInterval(() => {
if (this.time === 1) {
clearInterval(_this.interval)
}
this.time--
}, 1000)
if (this.pages > num) {
this._renderPage(num + 1)
}
})
},