使用pdfjs实现PDF的预览效果
核心部分是pdf.js和pdf.worker.js,一个负责API解析,一个负责核心解析
实现pdf预览主要有两种方式:
1、使用pdfjs已经写好的viewer.html页面。需要将pdfjs代码到服务器上,因为放到本地包有点大
2、将PDF文件渲染成Canvas
第一种方式:使用viewer.html,以读取文件流方式在线展示pdf文件
这种方法需要从官网上将pdf.js包下载下来
官网下载地址:https://mozilla.github.io/pdf.js/getting_started/#download.
下载后将pdf.js 放到服务器上 如:http://xxxx:8080/static/pdfjs
然后再使用iframe标签去显示
<iframe :src="url" width="100%" height="100%"></iframe>
this.pdfInfo.serverUrl = 'http://xxxx:8080/static/pdfjs/web/viewer.html'
this.pdfInfo.pdfUrl = 'http://xxxx:8080/XXX/getClausePdf?Code=1234' // 调取接口返回文件流
this.url = `${this.pdfInfo.serverUrl}?file=${encodeURIComponent(this.pdfInfo.pdfUrl)}`
第二种方式:将PDF文件渲染成Canvas,也是我使用的方法
安装
npm i pdfjs-dist
引入pdf.js
import PDFJS from 'pdfjs-dist'
const worderSrc = require('pdfjs-dist/build/pdf.worker.min.js')
html部分
<div class="pdf-container">
<canvas v-for="index in totalPage" :key="index" :id="`canvas-${index}`"></canvas>
</div>
核心代码
PDFJS.GlobalWorkerOptions.workerSrc = worderSrc
// this.pdfPath pdf地址,如果是流需单独处理一下
PDFJS.getDocument(this.pdfPath).promise.then(pdfDocument => {
this.totalPage = pdfDocument.numPages // 页码
for (let i = 1; i <= pdfDocument.numPages; i++) {
pdfDocument.getPage(i).then(pdfPage => {
let viewport = pdfPage.getViewport(2.0)
let canvas = document.getElementById(`canvas-${i}`)
canvas.width = viewport.width
canvas.height = viewport.height
let ctx = canvas.getContext('2d')
let renderTask = pdfPage.render({
canvasContext: ctx,
viewport: viewport
})
return renderTask.promise
})
}
}).catch(reason => console.error('PDF加载失败'))
如果后端返回的是流的形式,就用此方法转一下
/**
* 流转成url
*/
getObjectURL(file) {
let url = null
if (window.createObjectURL !== undefined) { // basic
url = window.createObjectURL(file)
} else if (window.webkitURL !== undefined) { // webkit or chrome
try {
url = window.webkitURL.createObjectURL(file)
} catch (error) {
console.log(error)
}
} else if (window.URL !== undefined) { // mozilla(firefox)
try {
url = window.URL.createObjectURL(file)
} catch (error) {
console.log(error)
}
}
return url
},
赠送一个下载
fileDownload() {
if (this.src) {
var tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = this.PDF // 解析好的地址
tempLink.setAttribute('download', this.fileName)
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(this.PDF)
} else {
this.$message.error('请选择需要导出的算法')
}
},