h5版本pdf預(yù)覽,使用pdfjs
1秃殉、安裝
npm install pdfjs-dist@2.0.943 --save
2坝初、編寫PDFJSUtil.js工具類
/**
* pdfjs
*/
import PDFJS from 'pdfjs-dist'
// owrker
import workerSrc from 'pdfjs-dist/build/pdf.worker'
// 設(shè)置work
// PDFJS.workerSrc = workerSrc;
PDFJS.GlobalWorkerOptions.workerSrc = workerSrc
//
let PDFJSUtil = {
// 加載pdf
async loadPdf({el, url, scale = 1.5}){
// dom對象
let pdfCol = $Fw.getEl(el);
// 創(chuàng)建pdf對象
let pdf = await PDFJS.getDocument(url);
// 獲取分頁
let pages = pdf.numPages;
// 循環(huán)添加
for (let i = 1; i <= pages; i++) {
let canvas = document.createElement('canvas')
let page = await pdf.getPage(i)
let viewport = page.getViewport(scale)
let context = canvas.getContext('2d')
canvas.height = viewport.height
canvas.width = viewport.width
let renderContext = {
canvasContext: context,
viewport: viewport
}
await page.render(renderContext)
canvas.className = 'canvas'
pdfCol.appendChild(canvas)
}
}
}
// 輸出
export default PDFJSUtil;
demo.vue
<template>
<div id="pdfid"></div>
</template>
<script>
import PDFJSUtil from './pdfjs/index.js'
export default {
data(){
return {}
},
/**
* 掛在dom
*/
mounted(){
// 加載pdfjs
PDFJSUtil.loadPdf({
// dom位置
el: '#pdfid',
// pdf地址
url: 'http://127.0.0.1:8099/test.pdf',
// 縮放比 默認1.5
// scale: 1.5
});
}
}
</script>
<style>
#pdfid {
height: 100vh;
width: 100%;
overflow: hidden;
}
</style>