Vue实现pdf、docx、jpg在线预览功能

Vue实现pdf、docx、jpg在线预览功能

  • PDF预览
  • docx、xls、ppt预览
    • docx预览(docx转HTML)
  • jpeg、jpg、png预览

PDF预览

<iframe id="preview" 
		:src="fileUrl" 
		frameborder="0"
        width="100%"
        :height="editHeight"
        :style="{ overflow: 'auto' }"
>iframe>
// pdf预览
API.common.previewFile(_res.data.id).then((res) => {
	if (this.filesType === 'pdf') {
		let blob = new Blob([res.data], {type: application})
	    let url = window.URL.createObjectURL(blob)
	    this.fileUrl = url
	}
})

docx、xls、ppt预览

<iframe :src="http://view.officeapps.live.com/op/view.aspx?src=http%3a%2f%2fvideo.ch9.ms%2fbuild%2f2011%2fslides%2fTOOL-532T_Sutter.docx" 
		frameborder="0"
        width="100%"
        :height="editHeight"
        :style="{ overflow: 'auto' }"

>iframe>

http://view.officeapps.live.com/op/view.aspx?src=<文档位置>

注意: <文档位置> 需要经过 URL 编码,资源必须是公共可访问的。

具体文档看微软接口文档

docx预览(docx转HTML)

由于公司是内网,所以不能使用微软提供的在线预览,需求是可以预览docx,在网上找到了以下方法,把docx文件转为html,然后渲染到页面

<div class="sub-skeleton-box" v-html="vHtml">div>
// word预览
API.common.previewFile(_res.data.id).then((res) => {
	if (this.filesType === 'docx') {
	    let reader = new FileReader()
	    reader.readAsArrayBuffer(res.data)
	    const that = this
	    reader.onload = function(e) {
	    	const buffer = e.target.result // 此时是arraybuffer类型
	        mammoth.convertToHtml({ arrayBuffer: buffer }).then((result) => {
	        	that.vHtml = result.value
	        })
	    }
	}
})

jpeg、jpg、png预览

<img :src="fileUrl" alt="" width="100%"/>
API.common.previewFile(_res.data.id).then((res) => {
	let blob = new Blob([res.data])
	let reader = new FileReader()
	const that = this
	reader.readAsDataURL(blob) // 转换为base64
	reader.onload = function() {
		that.fileUrl = reader.result
	}
})

你可能感兴趣的:(VUE,vue)