vue2 预览

该文章展示了如何在Vue.js应用中实现不同类型的文件预览,包括PDF、DOCX、XLSX等,利用vue-pdf库处理PDF,docx-preview处理DOCX文件,XLSX库解析Excel文件。代码中涉及文件加载、错误处理以及对话框的显示控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html

<el-button type="text" size="small" @click="watch(scope.row)" icon="el-icon-view">预览</el-button>


  <el-dialog :title="fileTitle" :visible.sync="dialogFileVisible" width="70%">
      <div class="file_content" v-loading="fileLoading" ref="pdfContent">
        <div v-show="!fileLoading">
          <div v-if="fileType === '1' || fileType === '3' || fileType === '6'">
            <PDF style="width:100%" v-for="i in pageNum" :key="i" :page="i" ref="pdf" :src="fileSrc" />
          </div>
          <div v-if="fileType === '2'" class="docx" ref="docxRef" />
          <div v-if="fileType === '4'" ref="excelRef" class="excelRef" />
        </div>
        <!--        <div v-if="fileType==='6'" ref="docRef" class="doc">
          <VueDocPreview :value="fileSrcData" type="office" />
        </div>-->
      </div>
      <el-backtop target=".el-dialog__body"></el-backtop>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFileVisible = false">取 消</el-button>
      </span>
    </el-dialog>

js

//下载引入插件
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import PDF from 'vue-pdf'
import * as XLSX from 'xlsx'
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
var docx = require('docx-preview')
window.JSZip = require("jszip");
//方法
 //预览
    watch(row) {
      this.fileType = '999'
      console.log(row);
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      //获取token
      getDownloadToken().then(res => {
        if (res && res.code == 200) {
          this.fileType = row.fileType
          const fileSrc = process.env.VUE_APP_BASE_API + "/xxxxxx/download/resource?resource=" + row.filepath
          this.fileSrcData = fileSrc
          this.fileTitle = row.filename
          if (row.fileType === '1') {
            this.fileSrc = ''
            this.fileLoading = true
            this.fileSrc = PDF.createLoadingTask({ url: fileSrc, CMapReaderFactory })
            this.fileSrc.promise.then(pdf => {
              this.pageNum = pdf.numPages
              this.fileLoading = false
            })
            loading.close()
            this.dialogFileVisible = true
            return
          }

          if (row.fileType === '2' || row.fileType === '6') {
            this.fileLoading = true
            //this.dialogFileVisible = true
            //console.log(document.getElementsByClassName('docx')[0]);
            this.dialogFileVisible = true
            this.$nextTick(() => {
              this.$refs.docxRef.innerHTML = ''
            })
            downEnv(row.filepath).then(res => {
              docx.renderAsync(res, this.$refs.docxRef).then((r1, r2) => {
                this.fileLoading = false
              })
            })
            loading.close()
            return;
          }
          if (row.fileType === '3') {
            this.fileLoading = true
            pptToPDF({ resource: row.filepath }).then(response => {
              const { msg } = response
              console.log(response, "777777");
              //this.dialogFileVisible = true
              const fileSrc1 = process.env.VUE_APP_BASE_API + "/common/download/resource?resource=" + msg
              this.fileSrc = PDF.createLoadingTask({ url: fileSrc1, CMapReaderFactory })
              console.log(this.fileSrc, "888888888");
              this.fileSrc.promise.then(pdf => {
                console.log(pdf, "99999999999999999999");
                this.pageNum = pdf.numPages
                this.fileLoading = false
              })
                .catch(err => {
                  console.log(err);
                  // this.fileLoading = false
                  // this.dialogFileVisible = false
                  // loading.close()
                  // this.$message("文件为空不可以浏览")
                })
            })
            loading.close()
            this.dialogFileVisible = true
            return;
          }
          if (row.fileType === '5') {
            this.imgList = []
            this.picSrc = fileSrc
            this.imgList.push(fileSrc)

            this.$refs.imgRef.showViewer = true
            loading.close()
            return;
          }
          if (row.fileType === '4') {
            //this.dialogFileVisible = true
            let binary = "";
            downEnv(row.filepath).then(res => {
              const bytes = new Uint8Array(res)
              const length = bytes.byteLength;
              for (let i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
              }
              const wb = XLSX.read(binary, { type: "binary" });
              const wsname = wb.SheetNames[0];
              const ws = wb.Sheets[wsname];
              const HTML = XLSX.utils.sheet_to_html(ws);
              if (this.$refs.excelRef) {
                this.$nextTick(() => {
                  //this.$refs.docxRef.innerHTML = ''
                  this.$refs.excelRef.innerHTML = HTML;
                })
              }
            })
            loading.close()
            this.dialogFileVisible = true
            return;
          }
          // if (row.documentType==='6') {
          //   loading.close()
          //   this.dialogFileVisible = true
          //   return;
          // }
          //直接下载
          this.downloadFiles(row)
          loading.close()
        }
      })
    },

Vue2预览PDF图片通常会涉及到将PDF文件转换成图片格式,比如JPG或PNG,然后在浏览器上显示这些静态图像。这可以通过一些库如html2canvas、jsPDF等工具来实现。以下是一个简单的步骤: 1. **安装依赖**:首先需要安装`html2canvas`库,可以使用npm或yarn: ```bash npm install html2canvas --save ``` 2. **创建PDF转图片函数**: ```javascript import html2canvas from 'html2canvas'; async function previewPdfAsImage(pdfElement) { const canvas = document.createElement('canvas'); let imgData; try { // 将PDF内容渲染到canvas await html2canvas(pdfElement).then((canvasResult) => { imgData = canvasResult.toDataURL('image/png'); // 转换为Base64数据URL }); } catch (error) { console.error('Error converting PDF to image:', error); } return imgData; // 返回图片数据URL } ``` 3. **在Vue组件中使用**: ```vue <template> <div ref="previewPdf"> <!-- 在这里插入你的PDF元素,例如嵌入的iframe --> <iframe :src="pdfSrc" @load="handlePdfLoad"></iframe> </div> </template> <script> export default { data() { return { pdfSrc: 'your-pdf-url-or-data', // PDF源地址 }; }, methods: { handlePdfLoad() { this.previewPdfAsImage(this.$refs.previewPdf).then((imgData) => { this.pdfPreviewUrl = imgData; // 存储图片数据,然后在视图中显示它 }); }, }, }; </script> ``` 4. **显示预览图片**: 在模板中添加一个`<img>`标签,动态绑定预览的图片URL: ```html <img :src="pdfPreviewUrl" alt="PDF Preview"> ``` 注意:这个方法并不是直接预览PDF,而是生成了一个静态的图片表示。如果PDF内容很大,可能会导致加载缓慢或内存占用过高。对于复杂的PDF交互体验,可能需要使用专门的PDF查看器插件或服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值