java 使用OpenOffice文件实现预览
1.安装OpenOffice软件
安装教程:https://jingyan.baidu.com/article/c275f6ba12c07ce33d756732.html
2.安装完成后,创建项目,pom重要的jar包
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.0.0-RELEASE</version>
</dependency>
3.核心代码
项目启动:
package com.example.demo; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
控制层代码:
package com.example.demo; import com.example.util.FileUtil;
import com.example.util.Office2PDF; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream; @ComponentScan
@Controller
@RequestMapping("/test")
public class ReadAndDownLoad {
//base路径
@Value("${BASE_PATH}")
private String BASE_PATH ; /**
*
* @return choose页面
*/
@RequestMapping("/choose")
public String chooseFile(){
return "ShowChoose";
} /**
*
* @param res 响应对象
* @param fileName 请求预览文件名
* @throws Exception
*/
@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();
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b)) != -1){
out.write(b);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(in != null){
in.close();
}
if(out != null){
out.close();
}
}
} /**
* 文件处理
* @param fileName
* @return
*/
public String fileHandler(String fileName){
String fileSuffix = FileUtil.getFileSuffix(fileName);
System.out.println(fileSuffix);
if("pdf".equals(fileSuffix))
{
return BASE_PATH + fileName;
}
else
{
return Office2PDF.openOfficeToPDF(BASE_PATH + fileName).getAbsolutePath();
} }
}
文件转换核心代码:
package com.example.util;
import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.DefaultOfficeManagerBuilder;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeManager; import java.io.File;
import java.util.regex.Pattern; public class Office2PDF {
//文件转换pdf成功后保存的地址
private static String SAVE_PATH = "E:/pdfFile/";
private Office2PDF(){} /**
* 将office格式的文件转为pdf
* @param sourceFilePath 源文件路径
* @return
*/
public static File openOfficeToPDF(String sourceFilePath){
return office2pdf(sourceFilePath);
} /**
* 将office文档转换为pdf文档
* @param sourceFilePath 原文件路径
* @return
*/
public static File office2pdf(String sourceFilePath){
OfficeManager officeManager = null;
try{
if(StringUtil.isEmpty(sourceFilePath))
{
//打印日志...
return null;
}
File sourceFile = new File(sourceFilePath);
if(!sourceFile.exists())
{
//打印日志...
return null;
} String after_convert_file_path = getAfterConverFilePath(sourceFilePath);
//启动openOffice
officeManager = getOfficeManager();
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
return convertFile(sourceFile,after_convert_file_path,sourceFilePath,converter);
}catch (Exception e){
e.printStackTrace();
System.out.println("转换异常");
}finally {
if(officeManager != null){
try {
officeManager.stop();
} catch (OfficeException e) {
e.printStackTrace();
}
}
}
return null;
} /**
* 转换文件
* @param sourceFile 原文件
* @param after_convert_file_path 转换后存放位置
* @param sourceFilePath 原文件路径
* @param converter 转换器
* @return
*/
public static File convertFile(File sourceFile,
String after_convert_file_path,String sourceFilePath,OfficeDocumentConverter converter) throws OfficeException {
File outputFile = new File(after_convert_file_path);
if(!outputFile.getParentFile().exists()){
//如果上级目录不存在也就是E:/pdfFile这个文件夹不存在则创建一个
outputFile.getParentFile().mkdirs();
}
converter.convert(sourceFile,outputFile);
return outputFile;
} public static OfficeManager getOfficeManager(){
DefaultOfficeManagerBuilder builder = new DefaultOfficeManagerBuilder();
builder.setOfficeHome(getOfficeHome());
OfficeManager officeManager = builder.build();
try {
officeManager.start();
} catch (OfficeException e) {
//打印日志
System.out.println("start openOffice Fail!");
e.printStackTrace();
}
return officeManager;
} /**
* 获取转换后文件存放的路径
* @param sourceFilePath 源文件
* @return
*/
public static String getAfterConverFilePath(String sourceFilePath){
//截取源文件文件名
String sourceFileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1);
return SAVE_PATH + sourceFileName.replaceAll("\\."+FileUtil.getFileSuffix(sourceFileName),".pdf");
} /**
* 获取openOffice的安装目录
* @return
*/
public static String getOfficeHome(){
String osName = System.getProperty("os.name");
if(Pattern.matches("Windows.*",osName))
{
return "C:/Program Files (x86)/OpenOffice 4";
}
else if(Pattern.matches("Linux.*",osName))
{
return "/usr/temp";
}
else if (Pattern.matches("Mac.*",osName))
{
return "/Application/openOfficeSoft";
}
return null;
}
}
工具类:
package com.example.util; public final class FileUtil {
private FileUtil(){} /**
* 获取后缀
* @param fileName 文件名
* @return 后缀名
*/
public static String getFileSuffix(String fileName){
if(StringUtil.isEmpty(fileName) || fileName.lastIndexOf(".")<0 ){
return "error";
}
return fileName.substring(fileName.lastIndexOf(".")+1);
}
}
package com.example.util; public final class StringUtil {
private StringUtil(){} public static boolean isEmpty(String target){
return "".equals(target) || null ==target;
}
}
页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件预览</title>
</head>
<body>
<p>文件预览:</p><button id="show1">点击预览</button>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$("#show1").click(function(){
window.open("http://localhost:8080/test/read/"+"qqq.ppt");
}); </script>
</body>
</html>
配置文件:
#返回的前缀 目录对应src/main/webapp下
spring.mvc.view.prefix=/
#返回的后缀
spring.mvc.view.suffix=.html
#预览文件的地址
BASE_PATH=C:/Users/Administrator/Desktop/
pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.0.0-RELEASE</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
项目结构如下:
java 使用OpenOffice文件实现预览的更多相关文章
- Java实现文件的预览
最近项目需要用到文件的预览功能,就开始在网上收集资料,学习了几种文件预览的方法.我集成到我项目内测试的有以下三种,最后使用的是第三种: 直接使用别人提供的服务 例如:office web 365 使用 ...
- 关于confluence上传文件附件预览查看时出现乱码的问题解决办法
在confluence上传excel文件,预览时发现乱码问题主要是因为再上传文件的时候一般是Windows下的文件上传,而预览的时候,是linux下的环境,由于linux下没有微软字体,所以预览的时候 ...
- 文件在线预览doc,docx转换pdf(一)
文件在线预览doc,docx转换pdf(一) 1. 前言 文档转换是一个是一块硬骨头,但是也是必不可少的,我们正好做的知识库产品中,也面临着同样的问题,文档转换,精准的全文搜索,知识的转换率,是知识库 ...
- confluence上传文件附件预览乱码问题(linux服务器安装字体操作)
在confluence上传excel文件,预览时发现乱码问题主要是因为再上传文件的时候一般是Windows下的文件上传,而预览的时候,是linux下的环境,由于linux下没有微软字体,所以预览的时候 ...
- kkfileview v2.0 发布,文件在线预览项目方案
kkfileview文件在线预览 此项目为文件文档在线预览项目解决方案,项目使用流行的spring boot搭建,易上手和部署,部署好后可以独立提供预览服务,使用http接口访问,不需要和应用集成,具 ...
- 基于开源方案构建统一的文件在线预览与office协同编辑平台的架构与实现历程
大家好,又见面了. 在构建业务系统的时候,经常会涉及到对附件的支持,继而又会引申出对附件在线预览.在线编辑.多人协同编辑等种种能力的诉求. 对于人力不是特别充裕.或者项目投入预期规划不是特别大的公司或 ...
- JS代码实用代码实例(输入框监听,点击显示点击其他地方消失,文件本地预览上传)
前段时间写前端,遇到一些模块非常有用,总结以备后用 一.input框字数监听 <!DOCTYPE html> <html lang="en"> <he ...
- asp.net word ecxel类型文件在线预览
asp.net word ecxel类型文件在线预览 首先得引用COM: Microsoft Excel 10 Object Library Microsoft Word 10 Object Libr ...
- office文件的预览
使用FlexPaper实现office文件的预览(C#版) 需求很简单,用户上传office文件(word.excel.ppt)后,可以预览上传的这些文件.搜索的相关的资料后.整理如下: Step1. ...
随机推荐
- gerrit+gitlab整合调试
- Google Closure Compiler 高级模式及更多思考(转)
前言 Google Closure Compiler 是 Google Closure Tools 的一员,在 2009 年底被 Google 释出,早先,有 玉伯 的 Closure Compile ...
- python2行代码调用程序
import win32api win32api.ShellExecute(0, 'open', r'C:\Users\TOPFEEL\AppData\Local\Postman\app-5.5.0\ ...
- Redis基础---链接管理
Redis连接 Redis AUTH命令是用来向服务器验证给定的密码. 如果密码与在配置文件中的口令相匹配,则服务器会返回OK状态码,并开始接受命令.否则,将返回一个错误,并且客户需要尝试新的密码. ...
- [转]position:fixed; 在IE9下无效果的问题
本文转自:http://www.cnblogs.com/xinwang/archive/2013/04/06/3002384.html 平常DIV+CSS布局时,position属性一般用absoul ...
- SQL中CRUD C——create 添加数据 R——read 读取数据 U——update 修改数据 D——delete 删除数据
在SQL server中对数据库的操作: 删除表:drop table 表名修改表:alter table 表名 添加列add 列名 列类型alter table 表名 drop column 列名 ...
- microPython 的逗比报错的问题
今天搞了一天,发现了各种问题,首先最终的解决办法就是重现刷固件!!!! 重刷固件就需要清除flash! cd C:\Users\sansong\AppData\Local\Programs\Pytho ...
- 上传一个npm包
1.先创建一个npm账号 https://www.npmjs.com/signup 2.在cmd里输入命令进入项目文件夹 3.使用npm init 命令创建一个package.json(确保nodej ...
- 关于使用Axis2 webservice 处理Fault响应时抛org.apache.axis2.AxisFault的分析
使用Axis2这个框架进行webservice协议通讯,期间出了个问题,我(CLIENT)请求后,当服务端返回符合协议的SOAP异常报文,例如<soap:fault> ... 我的程序直接 ...
- 分布式缓存系统Memcached[分享]
个人网站:http://www.51pansou.com memcached视频下载:memcached视频教程 memcached源码下载:memcached源码 Memcached是什么? Mem ...