Vue implementa la operación de vista previa de archivos pdf, word y excel de intranet

Tabla de contenido


Representaciones:

pdf:

palabra:

sobresalir:


Código:

1.pdf

<div v-if="type == 'pdf'" style="height:100%">
  <iframe  id="pdfIframe" @load="adjustIframe" :src="pdfurl" 
           type="application/x-google-chrome-pdf"></iframe>
</div>
axios.request({
    method: "GET", 
    url: '',//你的请求地址
    responseType: "arraybuffer",
    }).then((res) => {
  if (res) {
    let blob = new Blob([res.data], { type: "application/pdf;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    this.pdfurl = url;
    this.dialogVisible = true;
  } else {
    this.$notify.error({ title: "失败", message: "接口请求失败" });
  }
})
    // iframe高度
     adjustIframe() {
      var ifm = document.getElementById("pdfIframe");
      ifm.height = document.documentElement.clientHeight-50;
      ifm.width = document.documentElement.clientWidth-10;
    },

2.palabra

confiar

npm install docx-preview --save
<div class="docWrap" v-if="type == 'word'">
  <!-- 预览文件的地方(用于渲染) -->
  <div ref="file"></div>
</div>
 axios.request({
    method: "GET", 
    url: '',
    responseType: "arraybuffer",
}).then((res) => {
  if (res) {
  let docx = require("docx-preview");
  docx.renderAsync(res.data, this.$refs.file);
  this.dialogVisible = true;
} else {  
  this.$notify.error({ title: "失败", message: "接口请求失败" });
  }
})

3. sobresalir

confiar:

npm install xlsx --save
<div v-if="type == 'excel'">
  <div class="excel-view-container">
    <div id="excelView" v-html="excelView"></div>
  </div>
</div>
axios.request({
    method: "GET", 
    url: '',
    responseType: "arraybuffer",
}).then((res) => {  
    if (res) {
      const workbook = XLSX.read(new Uint8Array(res.data), {
      type: "array",
    }); // 解析数据
    const worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
    this.excelView = XLSX.utils.sheet_to_html(worksheet); // 渲染
    this.$nextTick(function () {
    // DOM加载完毕后执行,解决HTMLConnection有内容但是length为0问题。
    this.setStyle4ExcelHtml();
    });
    this.dialogVisible = true;
  } else {
       this.$notify.error({ title: "失败", message: "接口请求失败" });
   }
})
    // 设置Excel转成HTML后的样式
    setStyle4ExcelHtml() {
      const excelViewDOM = document.getElementById("excelView");
      console.log(1111111,excelViewDOM)
      if (excelViewDOM) {
        const excelViewTDNodes = excelViewDOM.getElementsByTagName("td"); // 获取的是HTMLConnection
        console.log(excelViewTDNodes);
        
        if (excelViewTDNodes) {
          const excelViewTDArr = Array.prototype.slice.call(excelViewTDNodes);
          console.log(excelViewTDArr);
          
          for (const i in excelViewTDArr) {
            const id = excelViewTDArr[i].id; // 默认生成的id格式为sjs-A1、sjs-A2......
            if (id) {
              const idNum = id.replace(/[^0-9]/gi, ""); // 提取id中的数字,即行号
              if (idNum && (idNum === "1" || idNum === 1)) {
                // 第一行标题行
                excelViewTDArr[i].classList.add("class4Title");
              }
              if (idNum && (idNum === "2" || idNum === 2)) {
                // 第二行表头行
                excelViewTDArr[i].classList.add("class4TableTh");
              }
            }
          }
        }
      }
    },
.viewItemFileDialog {
  /deep/ .el-dialog__body{
    padding:0
  }
  /deep/ table {
    width: 100% !important;
    border-collapse: collapse !important;
    border-spacing: 0 !important;
    text-align: center !important;
    border: 0px !important;
    overflow-x: auto !important;
  }
 
  /deep/ table tr td {
    border: 2px solid gray !important; 
    width: 300px !important;
    height: 33px !important;
  }
  /**整体样式 */
  /deep/ .excel-view-container {
    background-color: #ffffff;
  }
  /**标题样式 */
  /deep/ .class4Title {
    font-size: 22px !important;
    font-weight: bold !important;
    padding: 10px !important;
  }
  /**表格表头样式 */
  /deep/ .class4TableTh {
    /* font-size: 14px !important; */
    font-weight: bold !important;
    padding: 2px !important;
    background-color: #ccc !important;
  }
}

 código general

Método de visualización de archivos: haga clic en el botón para mostrar la ventana emergente -> archivo de vista previa de la ventana emergente

npm install xlsx --save
npm install docx-preview --save

botón 

<el-form-item label="附件" >
  <el-button title="点击下载" type="text" icon="el-icon-document" 
             @click="downloadFile(row.approveId)">{
   
   {row.fileName}}</el-button>
  <el-button title="点击预览" size="mini" type="primary" style="margin: 0 30px"
             @click="preview(row.approveId,row.fileName)">预览</el-button>
</el-form-item>

ventanas emergentes 

<!-- 预览文件 -->
    <el-dialog
      width="100%"
      fullscreen
      class="viewItemFileDialog"
      title="预 览"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
    <!-- word -->
      <div class="docWrap" v-if="type == 'word'">
        <!-- 预览文件的地方(用于渲染) -->
        <div ref="file"></div>
      </div>
     <!-- excel -->
      <div v-if="type == 'excel'">
        <div class="excel-view-container">
          <div id="excelView" v-html="excelView"></div>
        </div>
      </div>
     <!-- pdf -->
      <div v-if="type == 'pdf'" style="height:100%">
        <iframe  id="pdfIframe" @load="adjustIframe" :src="pdfurl"
          type="application/x-google-chrome-pdf"></iframe>
      </div>
    </el-dialog>

js

preview(id,fileName) {
       //判断文件类型type
        let type = fileName.endsWith('.pdf')?"pdf":fileName.endsWith(",doc")||fileName.endsWith(".docx")?"word":fileName.endsWith('.xls')||fileName.endsWith('.xlsx')?"excel":"other"
        this.type = type
        switch (type){
        case "pdf":
          getFile(id).then((res) => {
            if (res) {
              let blob = new Blob([res.data], { type: "application/pdf;charset=utf-8" });
              const url = URL.createObjectURL(blob);
              this.pdfurl = url;
              this.dialogVisible = true;
            } else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
            }
          }).catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
          });
          return
        case "word":
          getFile(id).then((res) => {
            if (res) {
              let docx = require("docx-preview");
              docx.renderAsync(res.data, this.$refs.file);
              this.dialogVisible = true;
            }
            else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
            }
          }).catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
          });
          return
        case "excel":
          axios.request({
            method: "GET", 
            url: ''+id,
            responseType: "arraybuffer",
          }).then((res) => {
            if (res) {
              const workbook = XLSX.read(new Uint8Array(res.data), {
                type: "array",
              }); // 解析数据
              const worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
              this.excelView = XLSX.utils.sheet_to_html(worksheet); // 渲染
              this.$nextTick(function () {
                // DOM加载完毕后执行,解决HTMLConnection有内容但是length为0问题。
                this.setStyle4ExcelHtml();
              });
              this.dialogVisible = true;
            } else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
            }
          }).catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
          });
          return
      }
    },

interfaz 

export function getFile(id) {
  return request({
    method: "GET", 
    url: ''+id,
    // 设置响应体类型
    // responseType: "arraybuffer", 
    responseType: "blob", 
    headers: {
      Accept: "application/octet-stream",
    },
  })
}

Supongo que te gusta

Origin blog.csdn.net/WX_nbclass/article/details/126222796
Recomendado
Clasificación