zoukankan      html  css  js  c++  java
  • Vue项目中实现pdf文件嵌套在网页内显示

    方案一:使用pdfjs插件将pdf嵌套在页面中的某个位置

    提示:

    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 = 6 + '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

    方案二:使用iframe将pdf嵌套在页面中的某个位置

    iframe如何使用: https://www.cnblogs.com/huihuihero/p/11971841.html

  • 相关阅读:
    Swift-自定义类的构造函数
    Swift-存储属性,计算属性,类属性
    iOS-UICollectionViewController协议及回调
    Swift-数组
    Swift-switch使用注意点
    Swift-setValuesForKeysWithDictionary
    解决IDEA Struts2 web.xml问题
    枚举类
    增强for循环 -- foreach循环
    静态导入
  • 原文地址:https://www.cnblogs.com/huihuihero/p/12888258.html
Copyright © 2011-2022 走看看