前端代码:
<template>
<el-dialog
title="图像浏览"
:close-on-click-modal="false"
width="70%"
top="10px"
:visible.sync="visible">
<el-row>
<el-col :span="24">
//显示多页
<div v-if="manyVisible" class="grid-content bg-purple-light" >
<pdf v-for="i in numPages" :key="i" :src="pdfSrc" :page="i"></pdf>
</div>
//显示单页
<div v-if="singleVisible" class="grid-content bg-purple-light">
<pdf
:src="pdfSrc"
:page="pdfPageNum"
>
</pdf>
<div>
<el-button @click="prePage()">上一页</el-button> <el-button @click="nextPage()">下一页</el-button>
</div>
</div>
</el-col>
</el-row>
</el-dialog>
</template>
<script>
import pdf from "vue-pdf"
export default {
data () {
return {
visible: false,
pdfSrc: '',
pdfPageNum: 1,
numPages:1,
manyVisible: false,
singleVisible: false
}
},
components: {
pdf,
},
methods: {
init () {
this.visible = true
//1.后台获取pdf"
let src = `/gen/gentable/imageShow/443a5ce9ab98e689ab5ce5bd92e6a1a3e69687e4bbb65c783134342d323032322d3030315c3030312e706466`
this.$http({
url: this.$http.adornUrl(src),
method: 'get',
params: this.$http.adornParams(),
responseType: 'arraybuffer'
}).then(({data}) =>{
this.manyVisible = true
let datas = new Uint8Array(data)
this.pdfSrc = datas
//显示多页
let loadingTask = pdf.createLoadingTask(datas)
loadingTask.promise.then(pdf => {
this.numPages = pdf.numPages
}).catch((err) => {
console.error('pdf加载失败')
})
})
//2.直接路径
// this.pdfSrc = "localhost:8080/jg/pdf/test.pdf"
// this.singleVisible = true
// let loadingTask = pdf.createLoadingTask(this.pdfSrc)
// loadingTask.promise.then(pdf => {
// this.numPages = pdf.numPages
// }).catch((err) => {
// console.error('pdf加载失败')
// })
},
nextPage() {
var p = this.pdfPageNum;
p = p < this.numPages ? p + 1 : 1;
this.pdfPageNum = p;
},
prePage() {
var p = this.pdfPageNum;
p = p > 1 ? p - 1 : 1;
this.pdfPageNum = p;
},
// 表单提交
dataFormSubmit () {
},
}
}
</script>
<style>
</style>
后端代码:
@GetMapping(value = "/imageShow/{path}")
public void imageShow(@PathVariable("path") String path, HttpServletResponse response) throws IOException {
String rpath = Encodes.decodeHexS(path);
File file = new File(rpath);
FileInputStream fis;
fis = new FileInputStream(file);
long size = file.length();
byte[] data = new byte[(int) size];
fis.read(data, 0, (int) size);
fis.close();
if(rpath.endsWith(".pdf")){
response.setContentType("application/pdf");
}else{
response.setContentType("image/png");
}
response.setHeader("Content-Disposition", "attachment; filename="+ Encodes.urlEncode(file.getName()));
OutputStream out = response.getOutputStream();
out.write(data);
out.flush();
out.close();
}