前导:
- 开发过程中经常会使用java将office系列文档转换为PDF, 一般都使用微软提供的openoffice+jodconverter 实现转换文档。
- openoffice既有windows版本也有linux版。不用担心生产环境是linux系统。
- 关于linux系统安装openoffice软件请参照:https://blog.youkuaiyun.com/liutianjie/article/details/87250553
1、openoffice依赖jar,以maven为例:
需注意:jodconverter2.2.1 在转换2007版本以后的xxx.docx文档会报错,原因是03版本后缀名xxx.doc 07以后版本xxx.docx
jodconverter2.2.2 支持docx、xlsx、pptx
<!-- openoffice 开始 -->
<!-- jodconverter2.2.2不能通过maven自动下载需要手动添加,具体下载添加请继续查看本文章 -->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- 以下依赖都可以通过maven自动下载 -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>3.0.1</version>
</dependency>
<!--jodconverter2.2.1必须依赖slf4j-jdk14必须这个版本,不然源码中日志会报错,很low的一个问题-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.4.3</version>
</dependency>
<!-- openoffice 结束 -->
1.1在Maven依赖中使用这个jodconverter-2.2.2.jar的方法
首先到这个地址去下载jar包
https://github.com/umlts/jodconverter-2.2.2
然后解压到Maven仓库的"com\artofsolving\jodconverter"这个路径下( 如果没有这个路径就创建 )
1.2 可能还需要的操作:
jodconverter-2.2.2异常
解决方法,手动添加Maven依赖:
首先下载jodconverter-2.2.2.jar(我是放在E:\jar文件夹下了)
打开cmd,执行命令:mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file -Dfile=E:\jar\jodconverter-2.2.2.jar
执行正常。
确认是否添加成功:maven资源库中setting.xml设置的路径下确认。
1.3后期将手动添加的此jodconverter-2.2.2.jar包上传到linux服务器上的nexus上即可。
到此,我们的配置依赖完成。
2、后台代码
package com.gainian.gjoa.web.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import util.Constants;
//import util.Doc2HtmlUtil;
import util.ResponseUtils;
import com.alibaba.fastjson.JSONObject;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
@Controller
@RequestMapping("/YulanUploadController")
public class YulanUploadController {
/**
* 上传图片4269
* @param pic
*/
@RequestMapping(value="/uploadPic.do",method =RequestMethod.POST)
public void uploadPic(@RequestParam(required = false) MultipartFile pic,HttpServletResponse response,HttpServletRequest request){
HttpSession session = request.getSession();
//扩展名
String ext = FilenameUtils.getExtension(pic.getOriginalFilename());
//图片名称生成策略
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
DateFormat df1 = new SimpleDateFormat("yyyy-MM");
//图片名称一部分
String format = df.format(new Date());
String format2 = df1.format(new Date());
//随机三位数
Random r = new Random();
// n 1000 0-999 99
for(int i=0 ; i<3 ;i++){
format += r.nextInt(10);
}
//实例化一个Jersey
Client client = new Client();
//保存数据库
String path = "upload/" +format2+"/"+ format + "." + ext;
//另一台服务器的请求路径是?
String url = Constants.IMAGE_URL + path;
//设置请求路径
WebResource resource = client.resource(url);
//发送开始 POST GET PUT
try {
resource.put(String.class, pic.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
//返回二个路径
JSONObject jo = new JSONObject();
jo.put("url", Constants.IMAGE_URL+path);
jo.put("path",path);
jo.put("name", pic.getOriginalFilename());
jo.put("type",ext);
NumberFormat nbf=NumberFormat.getInstance();
nbf.setMinimumFractionDigits(2);
String c="";
if(pic.getSize()>(1024L*1024L)) {
c = nbf.format(pic.getSize()/(double)(1024L*1024L));
c= c+"M";
}else if(pic.getSize()>1024L){
c = nbf.format(pic.getSize()/(double)1024L);
c= c+"KB";
} else if(pic.getSize()<1024L) {
c= c+"B";
}else if(pic.getSize()>(1024L*1024L*1024L)) {
c = nbf.format(pic.getSize()/(double)(1024L*1024L*1024L));
c= c+"G";
}
jo.put("daxiao",c);
ResponseUtils.renderJson(response, jo.toString());
}
/**
* 上传附件
* @param pic
* @throws IOException
*/
@RequestMapping(value="/yulanuploadFujian.do",method =RequestMethod.POST)
public void uploadFujian(@RequestParam(required = false) MultipartFile fujian,HttpServletResponse response,
HttpServletRequest request) throws IOException{
String path = "";
String ext = "";
//用于返回预览附件地址
//Map<String,Object> map = new HashMap<String,Object>();
String FangwenDizhi = "none";
//转换后文件名称
String htmFileName = null;
if (null!=fujian) {
//扩展名
ext = FilenameUtils.getExtension(fujian.getOriginalFilename());
//图片名称生成策略
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
DateFormat df1 = new SimpleDateFormat("yyyy-MM");
//图片名称一部分
String format = df.format(new Date());
String format2 = df1.format(new Date());
//随机三位数
Random r = new Random();
// n 1000 0-999 99
for(int i=0 ; i<3 ;i++){
format += r.nextInt(10);
}
//实例化一个Jersey
Client client = new Client();
//保存数据库
path = "upload/fujian/"+ format + "." + ext;
//另一台服务器的请求路径是?
String url = Constants.IMAGE_URL + path;
//设置请求路径
WebResource resource = client.resource(url);
//发送开始 POST GET PUT
try {
resource.put(String.class, fujian.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
//将上传文件下载到本地
//saveUrlAs.download(url, "D:\\OADocument", "POST",ext,format);
String URL = null;
//System.out.println("fileName---->"+filePath);
//创建不同的文件夹目录
String filePath = "/home/ubuntuservice/usr/java/tomcat8082/webapps/img-web/upload/fujian";
System.out.println("开始创建上传文档存储目录:"+filePath);
File file=new File(filePath);
//判断文件夹是否存在
if (!file.exists())
{
//如果文件夹不存在,则创建新的的文件夹
file.mkdirs();
}
System.out.println("创建上传文档存储目录成功:"+filePath);
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try
{
// 建立链接
URL httpUrl=new URL(url);
conn=(HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表单,默认get方式
String method = "POST";
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用缓存
conn.setUseCaches(false);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream=conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
//判断文件的保存路径后面是否以/结尾
if (!filePath.endsWith("/")) {
filePath += "/";
}
//写入到文件(注意文件保存路径的后面一定要加上文件的名称)
URL = filePath+format+"."+ext;
fileOut = new FileOutputStream(URL);
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = bis.read(buf);
//保存文件
while(length != -1)
{
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e)
{
e.printStackTrace();
System.out.println("抛出异常!!");
}
System.out.println("----------"+URL);
System.out.println("----------"+ext);
//Doc2HtmlUtil.GetZaiXianYulanAddress(URL, ext,format);
//仅支持if条件中的文件格式转换
if(ext.equals("doc") || ext.equals("docx") || ext.equals("xls") || ext.equals("xlsx") || ext.equals("ppt") || ext.equals("pptx")) {
String docFileName = null;
if("doc".equals(ext)){
docFileName = "doc_" + format + ".doc";
htmFileName = "doc_" + format + ".pdf";
}else if("docx".equals(ext)){
docFileName = "docx_" + format + ".docx";
htmFileName = "docx_" + format + ".pdf";
}else if("xls".equals(ext)){
docFileName = "xls_" + format + ".xls";
htmFileName = "xls_" + format + ".html";
}else if("xlsx".equals(ext)){
docFileName = "xlsx_" + format + ".xlsx";
htmFileName = "xlsx_" + format + ".html";
}else if("ppt".equals(ext)){
docFileName = "ppt_" + format + ".ppt";
htmFileName = "ppt_" + format + ".pdf";
}else if("pptx".equals(ext)){
docFileName = "pptx_" + format + ".pptx";
htmFileName = "pptx_" + format + ".pdf";
}else{
System.out.println("无法匹配文件类型");
}
//创建不同的文件夹目录
//测试服上的地址
//String tooFilePath = "/home/ubuntuservice/usr/java/tomcat8082/webapps/img-web/upload/fujian/YuLanFuJian/ltj.text";
//正式服上的地址
String tooFilePath = "/usr/java/tomcat/tomcat8082/webapps/img-web/upload/fujian/YuLanFuJian/ltj.text";
System.out.println("开始创建转换后文档存储目录:"+tooFilePath);
File file1 = new File(tooFilePath);
File fileParent = file1.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
file1.createNewFile();
System.out.println("创建转换后文档存储目录成功:"+tooFilePath);
//测试服上的地址
//String toFilePath = "/home/ubuntuservice/usr/java/tomcat8082/webapps/img-web/upload/fujian/YuLanFuJian/";
//正式服上的地址
String toFilePath = "/usr/java/tomcat/tomcat8082/webapps/img-web/upload/fujian/YuLanFuJian/";
//String toFilePath = yuLanurl;
File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName);
File docInputFile = new File(toFilePath + File.separatorChar + docFileName);
if (htmlOutputFile.exists())
htmlOutputFile.delete();
htmlOutputFile.createNewFile();
if (docInputFile.exists())
docInputFile.delete();
docInputFile.createNewFile();
/**
* 由fromFileInputStream构建输入文件
*/
try {
OutputStream os = new FileOutputStream(docInputFile);
if(os != null) {
int bytesRead = 0;
byte[] buffer = new byte[1024 * 8];
FileInputStream fileInputStream = null;
file = new File(URL);
fileInputStream = new FileInputStream(file);
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fileInputStream.close();
}
} catch (IOException e) {
}
OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1",8100);
try {
connection.connect();
} catch (ConnectException e) {
System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");
}
// convert
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
converter.convert(docInputFile, htmlOutputFile);
connection.disconnect();
// 转换完之后删除word文件
docInputFile.delete();
//uploadYuLanFiles.UploadFTP();
//测试服上的地址
//FangwenDizhi = "http://192.168.0.125:8082/img-web/upload/fujian/YuLanFuJian/"+htmFileName;
//正式服上的地址
FangwenDizhi = "http://47.92.232.125:8082/img-web/upload/fujian/YuLanFuJian/"+htmFileName;
}
}
//map.put("FangwenDizhi", FangwenDizhi);
System.out.println("预览文件访问地址连接:"+FangwenDizhi);
//返回二个路径
JSONObject jo = new JSONObject();
jo.put("url", Constants.IMAGE_URL+path);
jo.put("path",path);
jo.put("name", fujian.getOriginalFilename());
jo.put("type",ext);
NumberFormat nbf=NumberFormat.getInstance();
nbf.setMinimumFractionDigits(2);
String c="";
c = nbf.format(fujian.getSize()/(double)(1024L*1024L));
String d= c+"M";
jo.put("daxiao",d);
jo.put("FangwenDizhi",FangwenDizhi);
ResponseUtils.renderJson(response, jo.toString());
}
}