首页 > Web开发 > 详细

Vue项目中实现pdf文件嵌套在网页内显示

时间:2020-05-14 15:10:06      阅读:282      评论:0      收藏:0      [点我收藏+]

提示:

1、不兼容IE及兼容模式下的360浏览器(极速模式可以兼容),以上浏览器请自行为用户设置不兼容提醒
2、canvas画布是浮动在页面元素之上的,请知悉
3、这里pdf文件由后端接口返回,如:http://192.168.1.164/imgs/202004/1588144455734.pdf
4、若pdf渲染不出来,则考虑是否是因为pdf文件地址的跨域问题

效果图

技术分享图片

实现步骤

1、安装pdfjs依赖
yarn add pdfjs-dist 或  npm install pdfjs-dist --save

2、在页面某个位置使用canvas画布来渲染pdf文件
<canvas v-for="page in pages" :id="‘the-canvas‘+page" :key="page"></canvas>

3、data里注册pages
data(){
   pages:‘‘,  //pdf分页   
}

4、引入PDFJS ,并调用相关函数_renderPage(),_loadFile()
import PDFJS from ‘pdfjs-dist‘

methods:{
    _renderPage (num) {
            this.pdfDoc.getPage(num).then((page) => {
                let canvas = document.getElementById(‘the-canvas‘ + num)
                let ctx = canvas.getContext(‘2d‘)
                let dpr = window.devicePixelRatio || 1
                let bsr = ctx.webkitBackingStorePixelRatio ||
                ctx.mozBackingStorePixelRatio ||
                ctx.msBackingStorePixelRatio ||
                ctx.oBackingStorePixelRatio ||
                ctx.backingStorePixelRatio || 1
                let ratio = dpr / bsr
                let viewport = page.getViewport(screen.availWidth / page.getViewport(1).width)
                canvas.width = viewport.width * ratio
                canvas.height = viewport.height * ratio
                // canvas.style.width = viewport.width + ‘px‘
                canvas.style.width = 7 + ‘rem‘
                // canvas.style.height = viewport.height + ‘px‘
                ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
                let renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                }
                page.render(renderContext)
                if (this.pages > num) {
                    this._renderPage(num + 1)
                }
            })
        },
        _loadFile (url) {
            PDFJS.getDocument(url).then((pdf) => {
                this.pdfDoc = pdf
                this.pages = this.pdfDoc.numPages
                this.$nextTick(() => {
                    this._renderPage(1)
                })
            })
        },
}

5、调用函数传入pdf文件地址进行渲染
this._loadFile(pdfurl)
本文相关内容引自 https://www.jianshu.com/p/b48af7917656

Vue项目中实现pdf文件嵌套在网页内显示

原文:https://www.cnblogs.com/huihuihero/p/12888258.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!