Java后台实现pdf文件在浏览器中预览

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

  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值