VUE预览.xls .docx .pdf文件
.docx
<h2>word本地文件预览</h2>
<div class="my-component" ref="preview">
<input type="file" @change="preview" ref="file" />
</div>
import { renderAsync } from 'docx-preview'
window.JSZip = require('jszip')
preview(e) {
renderAsync(this.$refs.file.files[0], this.$refs.preview)
},
.xls
<h2>excel本地文件预览</h2>
<div class="excel">
<input type="file" @change="upload" />
</div>
import XLSX from 'xlsx'
upload(e) {
const reader = new FileReader()
var file = e.target.files[0]
reader.readAsArrayBuffer(file)
reader.onload = (event) => {
var data = new Uint8Array(event.target.result)
console.log(data)
var workbook = XLSX.read(data, { type: 'array' })
var sheetNames = workbook.SheetNames
var worksheet = workbook.Sheets[sheetNames[0]]
this.excelView = XLSX.utils.sheet_to_html(worksheet)
this.$nextTick(function() {
this.setStyle4ExcelHtml()
})
}
},
setStyle4ExcelHtml() {
const excelViewDOM = document.getElementById('excelView')
if (excelViewDOM) {
const excelViewTDNodes = excelViewDOM.getElementsByTagName('td')
if (excelViewTDNodes) {
const excelViewTDArr = Array.prototype.slice.call(excelViewTDNodes)
for (const i in excelViewTDArr) {
const id = excelViewTDArr[i].id
if (id) {
const idNum = id.replace(/[^0-9]/gi, '')
if (idNum && (idNum === '1' || idNum === 1)) {
excelViewTDArr[i].classList.add('class4Title')
}
if (idNum && (idNum === '2' || idNum === 2)) {
excelViewTDArr[i].classList.add('class4TableTh')
}
}
}
}
}
},
pdf
<pdf :page="currentPage" src="/static/pdf2.pdf" @num-pages="pageCount = $event" @page-loaded="currentPage = $event"></pdf>
{{ currentPage }} / {{ pageCount }}
<button v-if="this.currentPage > 1" @click="last()">last</button>
<button v-if="this.currentPage < this.pageCount" @click="next()">next</button>
</div>
<pdf v-for="i in numPages" :key="i" :src="src" :page="i"></pdf>
import pdf from 'vue-pdf'
var loadingTask = pdf.createLoadingTask('/static/pdf2.pdf')
data() {
return {
currentPage: 0,
pageCount: 0,
numPages: undefined,
src: loadingTask,
excelView: null,
}
},
mounted() {
this.src.promise.then((pdf) => {
this.numPages = pdf.numPages
})
},
methods: {
last() {
if (this.currentPage !== 1) {
this.currentPage--
}
},
next() {
this.currentPage++
},