Vue implements local preview of word (docx), excel (xlsx), and pdf files

Vue implements local preview of word (docx), excel (xlsx), and pdf files

Realize the effect:

By clicking the preview, the browser opens a new tab to display the content of the file
insert image description here
word effect:
insert image description here
pdf effect:
insert image description here
excel effect:
insert image description here

Early preparation:

word plugin:

npm install --save docx-preview

excel add-in:

npm install --save @handsontable/vue
npm install --save handsontable
npm install --save handsontable/i18n
npm install --save exceljs
The part of xlsx refers to the open source code of the bamboo industry boss, and the table style needs to be introduced into the code For all the content in the xlsx file, interested friends can source content
Demo address [1]: https://zhuye1993.github.io/file-view/dist/index.html
github address: https://github.com /zhuye1993/file-view/tree/master/src/vendors
insert image description here
The location used in this article, and the reference method
insert image description here

pdf plugin:

pdf.js download address
http://mozilla.github.io/pdf.js/getting_started/#download
The downloaded file can be placed in the following location
insert image description here

code:

1. Global method: officeView
// 文件预览
/*
*row: 包含fileUrl文件地址的对象
*that: vueRouter实例
 */
export const officeView = function(row, that) {
    
    
  // 获取文件类型
  const type = row.fileUrl.substring(row.fileUrl.lastIndexOf('.') + 1, row.fileUrl.length).toLowerCase()
  if (type.indexOf('pdf') !== -1) {
    
    
    // pdf预览
    const pdfSrc = 'pdf/web/viewer.html?file=' + encodeURIComponent(downloadUrl + row.fileUrl)
    // 打开新标签页
    window.open(pdfSrc, '_blank')
  } else if (type.indexOf('docx') !== -1) {
    
    
    // docx预览
    // 获取目标路由地址
    const routeUrl = that.resolve({
    
    
      name: 'OfficeView',
      query: {
    
    
        fileUrl: downloadUrl + row.fileUrl,
        fileType: 0
      }
    })
    // 打开新标签页
    window.open(routeUrl.href, '_blank')
  } else if (type.indexOf('xlsx') !== -1) {
    
    
    // xlsx预览
    // 获取目标路由地址
    const routeUrl = that.resolve({
    
    
      name: 'OfficeView',
      query: {
    
    
        fileUrl: downloadUrl + row.fileUrl,
        fileType: 1
      }
    })
    // 打开新标签页
    window.open(routeUrl.href, '_blank')
  } else {
    
    
    Message({
    
    
      type: 'error',
      message: '仅支持docx、pdf、xlsx文件预览,其它类型文件请下载查看'
    })
  }
}
2. The route jumps to the OfficeView file, which displays word and excel preview content
<template>
  <div>
    <!-- excel文件内容位置 -->
    <div ref="output" />
    <!-- wor文件内容位置 -->
    <div v-if="fileType == 0" id="container" />
  </div>
</template>

<script>
import {
      
       renderAsync } from 'docx-preview'
import renderSheet from './xlsxView'
export default {
      
      
  data() {
      
      
    return {
      
      
      fileUrl: null,
      fileType: 0,
      tableData: null,
      last: null
    }
  },
  created() {
      
      
    // 从路由地址中获取fileUrl,fileType
    this.fileUrl = this.$route.query.fileUrl ? this.$route.query.fileUrl : null
    this.fileType = this.$route.query.fileType ? parseInt(this.$route.query.fileType) : 0
    if (this.fileUrl == null) {
      
      
      this.$message({
      
      
        type: 'error',
        message: '文件地址无效,请刷新后重试'
      })
    }
    // 加载文件内容
    this.uploading(this.fileUrl)
  },
  methods: {
      
      
    // 加载文件内容
    uploading(file) {
      
      
      // 获取文件流
      const xhr = new XMLHttpRequest()
      xhr.open('get', file, true)
      xhr.responseType = 'blob'
      xhr.onload = () => {
      
      
        if (xhr.status === 200) {
      
      
          if (this.fileType === 0) {
      
      
            // word预览
            renderAsync(
              xhr.response,
              document.getElementById('container'),
              null,
              {
      
      
                className: 'docx', // 默认和文档样式类的类名/前缀
                inWrapper: true, // 启用围绕文档内容渲染包装器
                ignoreWidth: false, // 禁止页面渲染宽度
                ignoreHeight: false, // 禁止页面渲染高度
                ignoreFonts: false, // 禁止字体渲染
                breakPages: true, // 在分页符上启用分页
                ignoreLastRenderedPageBreak: true, // 禁用lastRenderedPageBreak元素的分页
                experimental: false, // 启用实验性功能(制表符停止计算)
                trimXmlDeclaration: true, // 如果为真,xml声明将在解析之前从xml文档中删除
                debug: false // 启用额外的日志记录
              }
            )
          } else {
      
      
            // 嵌入式预览excel
            this.displayResult(xhr.response)
          }
        }
      }
      xhr.send()
    },
    // 嵌入式预览excel
    displayResult(buffer) {
      
      
      // 生成新的dom
      const node = document.createElement('div')
      // 添加孩子,防止vue实例替换dom元素
      if (this.last) {
      
      
        this.$refs.output.removeChild(this.last.$el)
        this.last.$destroy()
      }
      const child = this.$refs.output.appendChild(node)
      // 调用渲染方法进行渲染
      return new Promise((resolve, reject) =>
        renderSheet(buffer, child).then(resolve).catch(reject)
      )
    }
  }
}
</script>

<style lang='scss' scoped>
#table {
      
      
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 60px;
  border: 1px solid #ebebeb;
  padding: 20px;
  width: 80%;
  margin: 40px auto;
  background-color: #fff;
  box-shadow:
  1.5px 1.2px 1.2px rgba(0, 0, 0, 0.014),
  3.3px 2.5px 2.7px rgba(0, 0, 0, 0.021),
  5.5px 4.3px 4.6px rgba(0, 0, 0, 0.027),
  8.3px 6.4px 6.9px rgba(0, 0, 0, 0.031),
  12px 9.3px 10px rgba(0, 0, 0, 0.035),
  17px 13.1px 14.2px rgba(0, 0, 0, 0.039),
  24.1px 18.6px 20.1px rgba(0, 0, 0, 0.043),
  35px 27px 29.2px rgba(0, 0, 0, 0.048),
  54px 41.6px 45px rgba(0, 0, 0, 0.055),
  96px 74px 80px rgba(0, 0, 0, 0.07);

  border-radius: 10px;
  overflow: scroll;
  height: 100%;

  .tab {
      
      
    margin: 0 0 20px 0;
    display: flex;
    flex-direction: row
  }
}
</style>

<style>
html{
      
      
  background-color: #edf2f7;
}
</style>
Call method:
<el-button size="mini" type="text" @click="$enum.pdfView(scope.row, $router)">预览</el-button>

Guess you like

Origin blog.csdn.net/qq_45158026/article/details/127308306