java 使用OpenOffice文件实现预览

1.安装OpenOffice软件

java 使用OpenOffice文件实现预览_第1张图片

安装教程:https://jingyan.baidu.com/article/c275f6ba12c07ce33d756732.html

2.安装完成后,创建项目,pom重要的jar包

 

1 
2 
3     org.jodconverter
4     jodconverter-core
5     4.0.0-RELEASE
6 
View Code

3.核心代码

项目启动:

 1 package com.example.demo;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 
 6 @SpringBootApplication
 7 public class DemoApplication {
 8 
 9     public static void main(String[] args) {
10         SpringApplication.run(DemoApplication.class, args);
11     }
12 }
View Code

 控制层代码:

 1 package com.example.demo;
 2 
 3 
 4 import com.example.util.FileUtil;
 5 import com.example.util.Office2PDF;
 6 
 7 import org.springframework.beans.factory.annotation.Value;
 8 import org.springframework.context.annotation.ComponentScan;
 9 import org.springframework.stereotype.Controller;
10 import org.springframework.web.bind.annotation.PathVariable;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 
13 import javax.servlet.http.HttpServletResponse;
14 import java.io.FileInputStream;
15 import java.io.InputStream;
16 import java.io.OutputStream;
17 
18 @ComponentScan
19 @Controller
20 @RequestMapping("/test")
21 public class ReadAndDownLoad {
22     //base路径
23     @Value("${BASE_PATH}")
24     private  String BASE_PATH ;
25     
26     
27 
28     /**
29      *
30      * @return choose页面
31      */
32     @RequestMapping("/choose")
33     public String chooseFile(){
34         return "ShowChoose";
35     }
36 
37     /**
38      *
39      * @param res 响应对象
40      * @param fileName 请求预览文件名
41      * @throws Exception
42      */
43     @RequestMapping("/read/{fileName}")
44     public void readFile(HttpServletResponse res , @PathVariable String fileName) throws Exception{
45         InputStream in = null;
46         OutputStream out = null;
47         String filePath =  fileHandler(fileName);
48         //判断是pdf还是word还是excel
49         //若是pdf直接读 否则转pdf 再读  //
50        try{
51            if(filePath != null){
52                in = new FileInputStream(filePath);
53            }
54            res.setContentType("application/pdf");
55            out = res.getOutputStream();
56            byte[] b = new byte[1024];
57            int len = 0;
58            while((len = in.read(b)) != -1){
59                out.write(b);
60            }
61        }catch (Exception e){
62            e.printStackTrace();
63        }finally {
64            if(in != null){
65                in.close();
66            }
67            if(out != null){
68                out.close();
69            }
70        }
71     }
72 
73     /**
74      * 文件处理
75      * @param fileName
76      * @return
77      */
78     public String fileHandler(String fileName){
79         String fileSuffix = FileUtil.getFileSuffix(fileName);
80         System.out.println(fileSuffix);
81         if("pdf".equals(fileSuffix))
82         {
83             return BASE_PATH + fileName;
84         }
85         else
86         {
87             return Office2PDF.openOfficeToPDF(BASE_PATH + fileName).getAbsolutePath();
88         }
89 
90     }
91 }
View Code

文件转换核心代码:

  1 package com.example.util;
  2 import org.jodconverter.OfficeDocumentConverter;
  3 import org.jodconverter.office.DefaultOfficeManagerBuilder;
  4 import org.jodconverter.office.OfficeException;
  5 import org.jodconverter.office.OfficeManager;
  6 
  7 import java.io.File;
  8 import java.util.regex.Pattern;
  9 
 10 public  class Office2PDF {
 11     //文件转换pdf成功后保存的地址
 12     private static   String SAVE_PATH = "E:/pdfFile/";
 13     private Office2PDF(){}
 14  
 15     /**
 16      * 将office格式的文件转为pdf
 17      * @param sourceFilePath 源文件路径
 18      * @return
 19      */
 20     public static   File openOfficeToPDF(String sourceFilePath){
 21         return office2pdf(sourceFilePath);
 22     }
 23 
 24     /**
 25      * 将office文档转换为pdf文档
 26      * @param sourceFilePath 原文件路径
 27      * @return
 28      */
 29     public static   File office2pdf(String sourceFilePath){
 30         OfficeManager officeManager = null;
 31         try{
 32             if(StringUtil.isEmpty(sourceFilePath))
 33             {
 34                 //打印日志...
 35                 return null;
 36             }
 37             File sourceFile = new File(sourceFilePath);
 38             if(!sourceFile.exists())
 39             {
 40                 //打印日志...
 41                 return null;
 42             }
 43 
 44             String after_convert_file_path = getAfterConverFilePath(sourceFilePath);
 45             //启动openOffice
 46             officeManager = getOfficeManager();
 47             OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
 48             return convertFile(sourceFile,after_convert_file_path,sourceFilePath,converter);
 49         }catch (Exception e){
 50             e.printStackTrace();
 51             System.out.println("转换异常");
 52         }finally {
 53            if(officeManager != null){
 54                try {
 55                    officeManager.stop();
 56                } catch (OfficeException e) {
 57                    e.printStackTrace();
 58                }
 59            }
 60         }
 61         return null;
 62     }
 63 
 64     /**
 65      * 转换文件
 66      * @param sourceFile 原文件
 67      * @param after_convert_file_path 转换后存放位置
 68      * @param sourceFilePath 原文件路径
 69      * @param converter 转换器
 70      * @return
 71      */
 72     public static File convertFile(File sourceFile,
 73                            String after_convert_file_path,String sourceFilePath,OfficeDocumentConverter converter) throws OfficeException {
 74         File outputFile = new File(after_convert_file_path);
 75         if(!outputFile.getParentFile().exists()){
 76             //如果上级目录不存在也就是E:/pdfFile这个文件夹不存在则创建一个
 77             outputFile.getParentFile().mkdirs();
 78         }
 79             converter.convert(sourceFile,outputFile);
 80         return outputFile;
 81     }
 82 
 83     public static OfficeManager getOfficeManager(){
 84         DefaultOfficeManagerBuilder builder = new DefaultOfficeManagerBuilder();
 85         builder.setOfficeHome(getOfficeHome());
 86         OfficeManager officeManager = builder.build();
 87         try {
 88             officeManager.start();
 89         } catch (OfficeException e) {
 90             //打印日志
 91             System.out.println("start openOffice Fail!");
 92             e.printStackTrace();
 93         }
 94         return officeManager;
 95     }
 96 
 97     /**
 98      * 获取转换后文件存放的路径
 99      * @param sourceFilePath 源文件
100      * @return
101      */
102     public static   String getAfterConverFilePath(String sourceFilePath){
103         //截取源文件文件名
104         String sourceFileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1);
105         return SAVE_PATH + sourceFileName.replaceAll("\\."+FileUtil.getFileSuffix(sourceFileName),".pdf");
106     }
107 
108     /**
109      * 获取openOffice的安装目录
110      * @return
111      */
112     public static String getOfficeHome(){
113         String osName = System.getProperty("os.name");
114         if(Pattern.matches("Windows.*",osName))
115         {
116             return "C:/Program Files (x86)/OpenOffice 4";
117         }
118         else if(Pattern.matches("Linux.*",osName))
119         {
120             return "/usr/temp";
121         }
122         else if (Pattern.matches("Mac.*",osName))
123         {
124             return "/Application/openOfficeSoft";
125         }
126         return null;
127     }
128 }
View Code

工具类:

 1 package com.example.util;
 2 
 3 public final  class FileUtil {
 4     private FileUtil(){}
 5 
 6     /**
 7      * 获取后缀
 8      * @param fileName 文件名
 9      * @return 后缀名
10      */
11     public static String getFileSuffix(String fileName){
12         if(StringUtil.isEmpty(fileName) || fileName.lastIndexOf(".")<0 ){
13             return "error";
14         }
15         return fileName.substring(fileName.lastIndexOf(".")+1);
16     }
17 }
View Code
1 package com.example.util;
2 
3 public final class StringUtil {
4     private StringUtil(){}
5 
6     public static boolean isEmpty(String target){
7         return "".equals(target) || null ==target;
8     }
9 }
View Code

页面代码:

 1 DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>文件预览title>
 6 head>
 7 <body>
 8     <p>文件预览:p><button id="show1">点击预览button>
 9     <script src="https://code.jquery.com/jquery-3.1.1.min.js">script>
10     <script>
11         $("#show1").click(function(){
12             window.open("http://localhost:8080/test/read/"+"qqq.ppt");
13         });
14         
15     script>
16 body>
17 html>
View Code

配置文件:

1 #返回的前缀   目录对应src/main/webapp下
2 spring.mvc.view.prefix=/
3 #返回的后缀
4 spring.mvc.view.suffix=.html
5 #预览文件的地址
6 BASE_PATH=C:/Users/Administrator/Desktop/
View Code

pom文件:

 1 
 2  3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     4.0.0
 5 
 6     com.example
 7     demo
 8     0.0.1-SNAPSHOT
 9     jar
10 
11     demo
12     Demo project for Spring Boot
13 
14     
15         org.springframework.boot
16         spring-boot-starter-parent
17         2.0.4.RELEASE
18          
19     
20 
21     
22         UTF-8
23         UTF-8
24         1.8
25     
26 
27     
28         
29             org.springframework.boot
30             spring-boot-starter-web
31         
32 
33         
34             org.springframework.boot
35             spring-boot-starter-test
36             test
37         
38 
39         
40         
41             org.jodconverter
42             jodconverter-core
43             4.0.0-RELEASE
44         
45 
46 
47     
48 
49     
50         
51             
52                 org.springframework.boot
53                 spring-boot-maven-plugin
54             
55         
56     
57 
58 
59 
View Code

项目结构如下:

java 使用OpenOffice文件实现预览_第2张图片

 

转载于:https://www.cnblogs.com/chLxq/p/10935708.html

你可能感兴趣的:(java 使用OpenOffice文件实现预览)