vue 预览 pdf 的具体使用

时间:2025-01-19 17:13:24

1、下载依赖

npm  install pdfjs-dist@2.2.228

2、在需要用的页面引入

<script>
   import * as PDFJS from 'pdfjs-dist';
   export default{
      data(){
          return{
            
        }
     },
     created(){
        = require('pdfjs-dist/build/')
     },
     mounted(){
       ()
     }
   }
</script>

3、其它都在methods

     //pdf 创建画布
     createPdfContainer(id,className) {
            var pdfContainer = ('pdf-container');
            var canvasNew =('canvas');
             = id;
             = className;
            (canvasNew);
             = false
     },
     // 渲染pdf 给pdf定宽度
     renderPDF(pdf,i,id) {
            (i).then(function(page) {
                var scale = 1.67;
                var viewport = (scale);
                //
                //  准备用于渲染的 canvas 元素
                //
                var canvas = (id);
                var context = ('2d');
                 = ;
                 = ;

                //
                // 将 PDF 页面渲染到 canvas 上下文中
                //
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                (renderContext);

            });
     },
        //创建和pdf页数等同的canvas数
    createSeriesCanvas(num,template) {
               const _this = this
            var id = '';
            for(var j = 1; j <= num; j++){
                id = template + j;
                _this.createPdfContainer(id,'pdfClass');
            }

     },
     hanle() {
          const _this= this
          _this.loadings = true
//如果pdf加密了 就用下面的obj
          let obj = {
               url:_this.dataurl,
               password:'你的密码'
          }
//如果pdf没有加密 就路径就好
    let obj = {
               url:_this.dataurl
          }
            (obj).then(function(pdf) {
                //用 promise 获取页面
                var id = '';
                var idTemplate = 'cw-pdf-';
                var pageNum = ;
                //根据页码创建画布
                _this.createSeriesCanvas(pageNum,idTemplate);
                //将pdf渲染到画布上去
                for (var i = 1; i <= pageNum; i++) {
                    id = idTemplate + i;
                    _this.renderPDF(pdf,i,id);
                }

            });
        },

4、页面

    <div class="left" ref="content">
               <div ref="pdfViewer"  class="pdfView" v-loading="loadings"></div>
             </div>