<template>
<div>
<el-upload class="upload-demo" :action="/file/upload/" accept=.pdf" name="upfile" :on-success="
(response, file, fileList) => {
return handleImgSuccess(response, file, fileList)
}
">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<div v-html="pdfContent"></div>
</div>
</template>
<script>
import pdfjsLib from "pdfjs-dist";
export default {
data() {
return {
pdfContent: "",
};
},
methods: {
handleImgSuccess(res, file) {
console.log(res, file);
const fileObj = file.raw;
if (fileObj.type === "application/pdf") {
const reader = new FileReader();
reader.onload = (e) => {
const arrayBuffer = e.target.result;
this.parsePdfFile(arrayBuffer);
};
reader.readAsArrayBuffer(fileObj);
} else {
this.$message.error("只能上传.pdf文件");
}
},
parsePdfFile(arrayBuffer) {
pdfjsLib
.getDocument(arrayBuffer)
.promise.then((pdf) => {
let pageNumber = 1;
let pagePromises = [];
while (pageNumber <= pdf.numPages) {
pagePromises.push(this.getPageText(pdf, pageNumber));
pageNumber++;
}
Promise.all(pagePromises)
.then((pages) => {
let text = "";
pages.forEach((page) => {
text += page;
});
this.pdfContent = text;
})
.catch((error) => {
console.error("解析.pdf文件失败", error);
});
})
.catch((error) => {
console.error("读取文件失败", error);
});
},
getPageText(pdf, pageNumber) {
return new Promise((resolve, reject) => {
pdf
.getPage(pageNumber)
.then((page) => {
page.getTextContent().then((textContent) => {
let text = "";
textContent.items.forEach((item) => {
text += item.str + " ";
});
resolve(text);
});
})
.catch((error) => {
reject(error);
});
});
},
},
};
</script>