在使用之前需要先进行引用 npm install --save vue-pdf
前台页面代码如下:
<template>
<div>
<pdf v-for="i in numPages" :key="i" :src="src" :page="i"></pdf>
</div>
</template>
<script>
import pdf from 'vue-pdf'
import { getPdf } from "../../api/test/test";
export default {
name: 'Pdf',
components: {
pdf
},
data() {
return {
pdfUrl: null,
numPages: 1
}
},
created() {
this.getpdf()
},
methods: {
getpdf() {
const that = this;
let formData = new FormData();
formData.append("pdfUrl", "https://dakaname.oss-cn-hangzhou.aliyuncs.com/file/2018-12-28/1546003237411.pdf");
getPdf(formData).then(data => {
//这个url就可以展示
//----that.pdfUrl = that.getObjectURL(data);
//我的需求是把每一页都要平铺展示在页面上,所以执行
that.pdfUrl = pdf.createLoadingTask(this.getObjectURL(res.data));
that.pdfUrl .promise.then(pdf => {
this.numPages = pdf.numPages;
});
console.log("pdfUrl", that.pdfUrl);
});
},
// 将返回的流数据转换为url
getObjectURL(file) {
let url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
try {
url = window.webkitURL.createObjectURL(file);
} catch (error) {
console.log(error)
}
} else if (window.URL != undefined) { // mozilla(firefox)
try {
url = window.URL.createObjectURL(file);
} catch (error) {
console.log(error)
}
}
return url;
},
}
}
</script>
import request from '@/utils/request'
export function getPdf(data) {
return request({
url: '/test/getPdf',
method: 'post',
responseType: 'blob',//这里是重点,一定不能落下
data: data
})
}
但是,如果你是在本地localhost环境请求后台接口返回的文件地址,一般都会跨域,如果要解决这个问题,需要把pdf文件在java端转换成文件流输出到前台,前台获取这个文件流后在前台展示,以下是后台代码请求示例,可根据自己的业务实现,后端代码如下:
package com.ruoyi.web.controller.test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@RestController
@RequestMapping("/test")
public class TestApiController {
@RequestMapping(value = "/getPdf", method = {RequestMethod.GET, RequestMethod.POST})
public void getPdf(String pdfUrl, HttpServletRequest req, HttpServletResponse resp) {
if (pdfUrl == null) {
pdfUrl = "";
}
resp.setContentType("application/pdf");
OutputStream sos = null;
BufferedInputStream bis = null;
try {
sos = resp.getOutputStream();
String destUrl = pdfUrl;
URL url = new URL(destUrl);
HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
//连接指定的网络资源
httpUrl.connect();
//获取网络输入流
bis = new BufferedInputStream(httpUrl.getInputStream());
int b;
while ((b = bis.read()) != -1) {
sos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
sos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}