后台读取本地文件转成流
@PostMapping("/getPdf")
public static void outPutLocal(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
File file = new File("C:/Users/molly.li/Desktop/变更流程.pdf");
FileInputStream fileInputStream = new FileInputStream(file);
response.setHeader("Content-Type", "application/pdf");
OutputStream outputStream = response.getOutputStream();
IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
前台引入
npm install --save vue-pdf
前台请求后台接口时需要明确类型responseType(主要)
如果不明确responseType的类型时,前台接收转换出的PDF文档为空白文档
import request from '@/plugins/request/index';
// 查询变更详细信息
export function outPutLocal (data) {
return request({
url: '/workbench/FileConversion/getPdf',
method: 'post',
data: data,
responseType: 'blob'
})
}
引入
// 调用的后台接口路径
import {outPutLocal} from "@api/epdmWorkbench/FileConversionApi";
// 引入的pdf
import PDF from 'vue-pdf'
<p-d-f
v-for="i in numPages"
:key="i"
:src="src"
:page="i"
class="pdf-set"
></p-d-f>
components: {PDF},
实现方法
// 查询pdf文件转换
previewPdfFile(){
let that = this
outPutLocal().then(res=>{
const blob = new Blob([res], { type: 'application/pdf' }) // res--后台返回的文件流
// 转换pdf的预览路径
this.src = that.getObjectURL(blob);
// 不分页查看PDF
this.loadPdf(this.src)
})
},
// 将返回的流数据转换为url
getObjectURL(file) {
let url = null;
if (typeof window.createObjectURL != 'undefined') { // basic
url = window.createObjectURL(file);
} else if (typeof window.webkitURL != 'undefined') { // webkit or chrome
try {
url = window.webkitURL.createObjectURL(file);
} catch (error) {
}
} else if (typeof window.URL != 'undefined') { // mozilla(firefox)
try {
url = window.URL.createObjectURL(file);
} catch (error) {
}
}
return url;
},
获取PDM的文件的页数
// 获取PDM的文件的页数
loadPdf (url) {
this.src = PDF.createLoadingTask(url)
this.src.promise.then(pdf => {
this.numPages = pdf.numPages // 这里拿到当前pdf总页数
})
},