方式1:将PDF
文件渲染成Canvas
<template>
<div class="canvas-container">
<canvas ref="myCanvas" class="pdf-container">
</canvas>
</div>
</template>
<script>
import pdfJS from 'pdfjs-dist'
pdfJS.GlobalWorkerOptions.workerSrc = 'pdfjs-dist/build/pdf.worker.js';
export default {
name:'pdfJs',
data() {
return {
loadFinished:false
}
},
methods: {
//预览pdf
previewPdfByUrl(url,scale) {
pdfJS.getDocument({
url
}).promise.then((pdf) => {
this.loadFinished = true
let numPages = pdf.numPages
let pageNumber = 1
this.getPage(pdf, pageNumber, numPages,scale)
})
},
//pdfData格式为:ArrayBuffer
previewPdfByData(pdfData,scale) {
// 引入pdf.js的字体(这里我没起效)
let CMAP_URL = 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/'
//读取base64的pdf流文件
pdfJS.getDocument({
data: pdfData, // PDF base64编码
cMapUrl: CMAP_URL,
cMapPacked: true
}).promise.then((pdf) => {
this.loadFinished = true
let numPages = pdf.numPages
let pageNumber = 1
this.getPage(pdf, pageNumber, numPages,scale)
})
},
getPage(pdf, pageNumber, numPages, scale=1) {
let _this = this
pdf.getPage(pageNumber).then((page) => {
// 获取DOM中为预览PDF准备好的canvasDOM对象
let canvas = _this.$refs.myCanvas
let viewport = page.getViewport({scale})
canvas.height = viewport.height
canvas.width = viewport.width
let ctx = canvas.getContext('2d')
let renderContext = {
canvasContext: ctx,
viewport: viewport
}
/**注意这里,是promise.then
原先是直接 .then(没有promise,则报过期的api)*/
page.render(renderContext).promise.then(() => {
pageNumber += 1
if (pageNumber <= numPages) {
_this.getPage(pdf, pageNumber, numPages)
}
})
})
},
//blob转arrayBuffer
blob2Array(blob) {
var reader = new FileReader()
reader.readAsArrayBuffer(blob)
reader.onload = function (e) {
return e.target.result
}
},
},
mounted() {
this.$nextTick(() => {
//通过请求等方式获取到data
let pdfData = ""
this.previewPdfByData(pdfData)
})
}
}
</script>
<style lang="scss" scoped>
.pdf-container {
width: 750px;
}
.canvas-container {
border: 1px dashed black;
position: relative;
}
</style>
方式2:viewer.html
1.到官网下载包v1.10.88/pdfjs-1.10.88-dist.zip
- 默认
viewer.html
打开的pdf
路径配置在viewer.js
如下:
var DEFAULT_URL = 'compressed.tracemonkey-pldi-09.pdf'
-
想要动态打开自己的
pdf
可以对应这块做修改 -
具体改法可参照使用pdfjs提供的viewer.html展示pdf文件流及其他方案
网友评论