Java后台实现pdf文件在浏览器中预览
放在服务器的pdf文件不能通过完整路径访问,想要实现的效果是浏览器访问后台接口可以预览pdf文件,暂时是把pdf文件放在本地测试
通过输出流的方式将pdf文件输出
1.项目中使用Spring+SpringBoot+Mybatis
2.工具类
/**
* 预览pdf文件工具类
* @param response
* @param fileName
*/
public static void showPdf( HttpServletResponse response, String fileName) throws IOException{
response.setContentType("application/pdf");
FileInputStream in = new FileInputStream(new File(fileName));
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
while ((in.read(b))!=-1) {
out.write(b);
}
out.flush();
in.close();
out.close();
}
3.controller层
@GetMapping("/test1")
@ApiOperation(value = "大健康-我的-模板合同查看")
public Response test1( HttpServletResponse response){
try {
// 本地的pdf文件
String path="D:\\document\\jys-fund\\test1.pdf";
fileUtil.showPdf(response,path);
return Response.create().success();
}catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
return Response.create().error(e.getMessage());
}
}
就能实现在浏览器访问http://localhost:8085/test1 预览这个pdf文件了
第一次写,有点简单,也希望与各位大神交流qq:907025187