1.安装OpenOffice软件
安装教程:https://jingyan.baidu.com/article/c275f6ba12c07ce33d756732.html
2.安装完成后,创建项目,pom重要的jar包
1 <!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core --> 2 <dependency> 3 <groupId>org.jodconverter</groupId> 4 <artifactId>jodconverter-core</artifactId> 5 <version>4.0.0-RELEASE</version> 6 </dependency>
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 }
控制层代码:
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 }
文件转换核心代码:
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 }
工具类:
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 }
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 }
页面代码:
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>
配置文件:
1 #返回的前缀 目录对应src/main/webapp下 2 spring.mvc.view.prefix=/ 3 #返回的后缀 4 spring.mvc.view.suffix=.html 5 #预览文件的地址 6 BASE_PATH=C:/Users/Administrator/Desktop/
pom文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 6 <groupId>com.example</groupId> 7 <artifactId>demo</artifactId> 8 <version>0.0.1-SNAPSHOT</version> 9 <packaging>jar</packaging> 10 11 <name>demo</name> 12 <description>Demo project for Spring Boot</description> 13 14 <parent> 15 <groupId>org.springframework.boot</groupId> 16 <artifactId>spring-boot-starter-parent</artifactId> 17 <version>2.0.4.RELEASE</version> 18 <relativePath/> <!-- lookup parent from repository --> 19 </parent> 20 21 <properties> 22 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 23 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 24 <java.version>1.8</java.version> 25 </properties> 26 27 <dependencies> 28 <dependency> 29 <groupId>org.springframework.boot</groupId> 30 <artifactId>spring-boot-starter-web</artifactId> 31 </dependency> 32 33 <dependency> 34 <groupId>org.springframework.boot</groupId> 35 <artifactId>spring-boot-starter-test</artifactId> 36 <scope>test</scope> 37 </dependency> 38 39 <!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core --> 40 <dependency> 41 <groupId>org.jodconverter</groupId> 42 <artifactId>jodconverter-core</artifactId> 43 <version>4.0.0-RELEASE</version> 44 </dependency> 45 46 47 </dependencies> 48 49 <build> 50 <plugins> 51 <plugin> 52 <groupId>org.springframework.boot</groupId> 53 <artifactId>spring-boot-maven-plugin</artifactId> 54 </plugin> 55 </plugins> 56 </build> 57 58 59 </project>
项目结构如下: