h5版本pdf预览,使用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'
// 设置work
// PDFJS.workerSrc = workerSrc;
PDFJS.GlobalWorkerOptions.workerSrc = workerSrc
//
let PDFJSUtil = {
// 加载pdf
async loadPdf({el, url, scale = 1.5}){
// dom对象
let pdfCol = $Fw.getEl(el);
// 创建pdf对象
let pdf = await PDFJS.getDocument(url);
// 获取分页
let pages = pdf.numPages;
// 循环添加
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>