实现pdf预览主要有两种方式:
1、使用pdfjs已经写好的viewer.html页面。需要将pdfjs代码到服务器上,因为放到本地包有点大
2、将PDF文件渲染成Canvas
方案一 使用pdf.js时,需要传入文件路径,若我们拿到的文件是流那么需要先执行以下操作
var blob = new Blob([stream], {type: 'application/pdf'});
var fileOfBlob = new File([blob], fileName || new Date().getTime() + '.pdf');
var fileUrl = window.URL.createObjectURL(fileOfBlob );
打开方式
// waterMark pdf水印
// file 打开的pdf
window.open('/viewer.html?file=' + fileUrl + '&waterMark=' + '测试' + '&fileName=' + '测试');
方案二 vue工程中使用
// 安装
npm i pdfjs-dist
import PDFJS from 'pdfjs-dist'
template
<canvas v-for="item in totalPage" :key="item" :id='"the-canvas" + item' class="pdf-content"></canvas>
method
let winW = document.documentElement.clientWidth
let loadingTask = PDFJS.getDocument(this.pdfFile)
loadingTask.promise.then(function (pdf) {
let pageNum = pdf.numPages
for (let i = 1; i <= pageNum; i++) {
pdf.getPage(i).then(function (page) {
let viewport = page.getViewport(1)
let scale = (winW / viewport.width).toFixed(2)
let scaledViewport = page.getViewport(scale)
let canvas = document.getElementById('the-canvas' + i)
let context = canvas.getContext('2d')
canvas.height = scaledViewport.height
canvas.width = scaledViewport.width
let renderContext = {
canvasContext: context,
viewport: scaledViewport
}
let renderTask = page.render(renderContext)
renderTask.then(function () {
})
})
}
}, function (reason) {
console.error(reason)
})
网友评论