关于java预览pdf

之前在项目中做了一个转pdf格式的需求,网上查了一些资料把完成了。用的是工具转换,今天主要说一些在线预览pdf的java代码的书写,如果需要了解工具的话可以留言,有时间我会把对应的代码整理出来。

不多说,直接上代码。

这个是通过文件的对应路径filePath 来进行访问的

@RequestMapping("/read/{fileName}")
public void readFile(HttpServletResponse res , @PathVariable String fileName) throws Exception{
    InputStream in = null;
    OutputStream out = null;
     //请忽略这段代码
    String filePath =  fileHandler(fileName);
    //判断是pdf还是word还是excel
    //若是pdf直接读 否则转pdf 再读  
   try{
       if(filePath != null){
           in = new FileInputStream(filePath);
       }
       res.setContentType("application/pdf");
       out = res.getOutputStream();
       
       ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
       byte[] buff = new byte[1024]; //buff用于存放循环读取的临时数据
       int rc = 0;
       while ((rc = in.read(buff, 0, 1024)) > 0) {
           swapStream.write(buff, 0, rc);
       }
      //in2b为转换之后的结果
       byte[] in2b = swapStream.toByteArray(); 

       out.write(in2b);

   }catch (Exception e){
       e.printStackTrace();
   }finally {
       if(in != null){
           in.close();
       }
       if(out != null){
           out.close();
       }
   }
}

由于现在有很多童鞋是通过文件服务器下载后在查看,所以需要转换一下流的形式

@RequestMapping("/read/{fileCode}")
public void readFile(HttpServletResponse res , @PathVariable String fileCode) throws Exception{
    InputStream in = null;
    OutputStream out = null;
    //已知是pdf格式,通过code从文件服务器下载
   byte[] fileStream = downFile(fileCode);
   try{
       if(filePath != null){
           in = new ByteArrayInputStream(fileStream );
       }
       res.setContentType("application/pdf");
       out = res.getOutputStream();

      //buff用于存放循环读取的临时数据
       byte[] buff = new byte[1024]; 
       int rc = 0;
       while ((rc = in.read(buff)) != -1) {
          out.write(buff);
       }
     
   }catch (Exception e){
       e.printStackTrace();
   }finally {
       if(in != null){
           in.close();
       }
       if(out != null){
           out.close();
       }
   }
}

前端代码只需要open一下即可

window.open("http://localhost:8080/test/read/"+"zz.pptx");

 window.open("http://localhost:8080/test/read/"+对应文件code);

搞定

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值