vue2中预览pdf、xlsx、xls、doc、docx

文章描述了一个使用Vue框架和相关库(如VueDocPreview和axios)实现的在线预览功能,支持docx、PDF和Excel文件,通过API请求获取文件并进行格式渲染。
摘要由CSDN通过智能技术生成

页面:

<el-dialog
      title="在线预览"
      :visible.sync="dialogVisible"
      width="80%"
      v-dialogDrag
      class="pub_dialog"
      :before-close="handleClose">
      <div v-show="docx">
        <div class="docWrap" style="background-color: white">
          <!-- 预览文件的地方(用于渲染) -->
          <div ref="file" style="background-color: white"></div>
        </div>
      </div>
      <div v-show="pdf">
        <iframe
          :src="pdfurl"
          type="application/x-google-chrome-pdf"
          style="width: 100%;height: 900px;"
        />
      </div>
      <div v-show="excel">
        <div class="excel-view-container">
          <div id="excelView" v-html="excelView" style="width: 90%;height: 900px;margin-left: 5%"></div>
        </div>
      </div>
</el-dialog>

js:

import XLSX from 'xlsx/xlsx.js'
import VueDocPreview from 'vue-doc-preview'


export default {
    components: { VueDocPreview },
    data(){
      return{
        doc : false;
        pdf : false;
        excel : false;
        // 还有其他的自行补充定义
      };
    },
    methods:{
      openDialog(row){
      this.doc = false;
      this.pdf = false;
      this.excel = false;
      console.log(row.path)
      this.dialogVisible = true
      if(row.name.endsWith('docx')){
        this.docx = true;
        axios
          .request({
            method: "GET", //这个不解释了吧
            url: url + '/doc/getFile?path=' + encodeURIComponent(row.path), //编码
            responseType: "blob", //告诉服务器想到的响应格式
          })
          .then((res) => {
            console.log(res)
            if (res) {
              let docx = require("docx-preview");
              docx.renderAsync(res.data, this.$refs.file);
              console.log(res.data)
            } else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
              this.loading = false;
            }
          })
          .catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
            console.log(error);
            this.loading = false;
          });
      }else if(row.name.endsWith('pdf')){
        this.pdf = true;
        axios
        .request({
          method: "GET", //这个不解释了吧
          url: url + '/doc/getFile?path=' + row.path,
          responseType: "blob", //告诉服务器想到的响应格式
          headers: {
            "Content-Type": "application/pdf;charset=UTF-8",
          },
        })
          .then((res) => {
            console.log(res);
            if (res) {
              let blob = new Blob([res.data], { type: "application/pdf" });
              const url = URL.createObjectURL(blob);
              console.log(url);
              this.pdfurl = url;
            } else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
            }
          })
          .catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
            console.log(error);
          });
      }else if(row.name.endsWith('xlsx') || row.name.endsWith('xls')){
        this.excel = true;
        axios
          .request({
            method: "GET", //这个不解释了吧
            url: url + '/doc/getFile?path=' + row.path,
            responseType: "arraybuffer", //告诉服务器想到的响应格式
            headers: {
              "Content-Type":
                "application/vnd.ms-excel;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            },
          })
          .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.setStyle4ExcelHtml();
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    }
  }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue预览docxdocpdfxlsxlsx文件,可以使用第三方来实现。 对于docxdocxlsxlsx文件,可以使用`js-xlsx`来进行解析和预览。该可以将Excel文件转换为JSON格式,而对于Word文件,可以使用`docx.js`来进行解析和预览。 对于pdf文件,可以使用`pdf.js`来进行预览。该可以通过Canvas将PDF文件渲染成图片,然后在Vue显示。 下面是一个示例代码,演示如何使用上述预览不同类型的文件: ```html <template> <div> <div v-if="fileType === 'docx' || fileType === 'doc'"> <div v-html="docContent"></div> </div> <div v-else-if="fileType === 'xls' || fileType === 'xlsx'"> <table> <tr v-for="row in excelData"> <td v-for="cell in row">{{ cell }}</td> </tr> </table> </div> <div v-else-if="fileType === 'pdf'"> <canvas ref="pdfCanvas"></canvas> </div> </div> </template> <script> import XLSX from 'xlsx'; import Docx from 'docx'; import pdfjsLib from 'pdfjs-dist'; export default { data() { return { fileType: '', docContent: '', excelData: [], }; }, mounted() { // 根据文件类型进行解析和预览 if (this.fileType === 'docx' || this.fileType === 'doc') { const reader = new FileReader(); reader.onload = (event) => { const content = event.target.result; const doc = new Docx(); doc.load(content); this.docContent = doc.getHtml(); }; reader.readAsArrayBuffer(this.file); } else if (this.fileType === 'xls' || this.fileType === 'xlsx') { const reader = new FileReader(); reader.onload = (event) => { const content = event.target.result; const workbook = XLSX.read(content, { type: 'array' }); const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; this.excelData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); }; reader.readAsArrayBuffer(this.file); } else if (this.fileType === 'pdf') { const canvas = this.$refs.pdfCanvas; const ctx = canvas.getContext('2d'); pdfjsLib.getDocument(this.file).promise.then((pdf) => { pdf.getPage(1).then((page) => { const viewport = page.getViewport({ scale: 1.5 }); canvas.height = viewport.height; canvas.width = viewport.width; page.render({ canvasContext: ctx, viewport, }); }); }); } }, props: { file: { type: File, required: true, }, }, created() { // 根据文件后缀名判断文件类型 const fileExtension = this.file.name.split('.').pop(); if (fileExtension === 'docx' || fileExtension === 'doc') { this.fileType = 'docx'; } else if (fileExtension === 'xls' || fileExtension === 'xlsx') { this.fileType = 'xls'; } else if (fileExtension === 'pdf') { this.fileType = 'pdf'; } }, }; </script> ``` 在上述代码,根据文件后缀名判断文件类型,然后使用不同的进行解析和预览。对于Word文件,使用`docx.js`文件解析为HTML格式,然后在Vue显示;对于Excel文件,使用`js-xlsx`文件解析为JSON格式,然后在Vue生成表格;对于PDF文件,使用`pdf.js`文件渲染成图片,然后在Vue显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值