Vue前端预览pdf

130 阅读1分钟

影像文件预览:

html:
<!-- 文件预览弹窗 -->
    <ui-dialog :close-on-click-modal="false" title="预览" :visible.sync="viewVisible" append-to-body width="80%">
      <div class="file-wrap">
        <img
          :src="fileUrl"
          style="width: 100%"
          alt=""
          v-if="currentFileExt === 'jpg' || currentFileExt === 'jpeg' || currentFileExt === 'gif' || currentFileExt === 'png'"
        />

        <div class="scrollBox" v-else-if="currentFileExt === 'pdf'">
          <pdf v-for="item in numPages" :key="item" :src="fileUrl" :page="item" ref="pdf"></pdf>
        </div>
        <!-- <div class="height500 no-data" v-else>不支持的文件格式 <span>点击下载</span></div> -->
        <div class="height500 no-data" v-else>不支持的文件格式</div>
        <div class="left-arrow arrow" @click="handleArreaClick('left')" v-if="viewImgList.length > 1">
          <i class="ui-icon-arrow-left"></i>
        </div>
        <div class="rignt-arrow arrow" @click="handleArreaClick('right')" v-if="viewImgList.length > 1">
          <i class="ui-icon-arrow-right"></i>
        </div>
      </div>
    </ui-dialog>Ï
    ------------------------------------------------------------------
    
    引入pdf
    import pdf from 'vue-pdf';

    ------------------------------------------------------------------
   // 影像文件预览
    viewFile(row, index) {
      this.getViewData(row, index);
      this.viewVisible = true;
    },
    getViewData(row, index) {
      this.currentFileExt = row.filePath.split('.')[1];
      this.fileIndex = index;
      if (this.currentFileExt === 'pdf') {
        // this.getNumPages();
        this.fileUrl = this.getObjectURL(row.downloadUrl);
      } else {
        this.fileUrl = row.downloadUrl;
      }
    },
    getObjectURL(downloadUrl) {
      let url = null;
      url = pdf.createLoadingTask({
        url: downloadUrl,
        cMapUrl: '/static/cmaps/',
        cMapPacked: true,
      });
      // 获取pdf页数
      url.promise
        .then((pdf) => {
          this.numPages = pdf.numPages;
        })
        .catch(() => {
          console.error('pdf 加载失败');
        });
      return url;
    }
 ----------------------------------------------------------------