在前端上传一个pdf文件,后端识别pdf文件,并返回识别后的word文件路径,前端再根据文件路径直接在页面展示解析word文件的结果,如下图:
上传文件后,先直接预览pdf文件
然后点击文字识别,右边则展示解析的word文件
实现过程
首先需要npm安装两个插件,一个预览pdf的插件vue-pdf,一个读取word文件的插件docx-preview
上传组件代码
<el-upload ref="upload" action="#" :on-remove="handleRemove" :on-preview="showPdf"
:limit="1" :file-list="picList" :auto-upload="false" :on-change="PicChange" :show-file-
list="true" accept=".pdf">
<el-button style="background-color: #fff;color: #00477d;width:
300px;height: 40px; border-color: #fff;font-size: 16px;font-weight: bold;box-shadow: 0px 2px 8px 2px rgba(0,71,125,0.1)">
+上传PDF文件
</el-button>
</el-upload>
预览pdf的代码
<div class="pdf_wrapper" style="height: 500px;overflow-y: scroll;" v-if="pdfUrl" v-loading="loading">
<pdf
v-for="i in pdfTotal"
:key="i"
:src="pdfUrl"
:page="i"
@page-loaded="handlePdfLoaded"
ref="pdf"
>
</pdf>
</div>
fileEventPic(data) {
this.picFiles = data;
console.log("picFiles",this.picFiles);
this.showPdf(this.picFiles[0])
},
PicChange(file, PicList) {
// 图片显示前做一下判断
const IMG_ALLOWD = ["pdf"]
let typeList = file.raw.type.split("/")
const imgType = typeList[typeList.length - 1]
const imgSize = file.size / 1024 / 1024
this.PicList = PicList
this.fileEventPic(this.PicList)
},
showPdf(file) {
this.loading = true;
let url=''
// if(this.actionType==0){
url = window.URL.createObjectURL(file.raw); //将文件转化成url
// }else{
// url = file.url; //将文件转化成url
// }
console.log(url, "pdfwenjain ");
this.pdfUrl = url;
let loadingTask = pdf.createLoadingTask(url);
loadingTask.promise
.then((pdf) => {
this.pdfTotal = pdf.numPages;
})
},
handleRemove(){
this.pdfTotal = 0
},
handlePdfLoaded(e) {
if (e === this.pdfTotal) {
this.$nextTick(() => {
setTimeout(() => {
this.loading = false;
}, 500);
});
}
},
读取word文件并展示
async getWord (){
const res2 = await axios(this.wordUrl, { responseType:'blob' })
this.previewWord(res2.data)
},
previewWord (ab, dom = null) {
const domEle = dom || this.$refs.wordDisplay
renderAsync(ab, dom || domEle, null, {
className: 'docx',
})
},
基本上就是这些啦,小小记录一下