前导:

  1. 开发过程中经常会使用java将office系列文档转换为PDF, 一般都使用微软提供的openoffice+jodconverter 实现转换文档。
  2. openoffice既有windows版本也有linux版。不用担心生产环境是linux系统。
  3. 关于linux系统安装openoffice软件请参照:https://blog.csdn.net/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   99for(int i=0 ; i<3 ;i++){format += r.nextInt(10);}//实例化一个JerseyClient client = new Client();//保存数据库String path = "upload/" +format2+"/"+ format + "." + ext;//另一台服务器的请求路径是?String url = Constants.IMAGE_URL  + path;//设置请求路径WebResource resource = client.resource(url);//发送开始  POST  GET   PUTtry {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   99for(int i=0 ; i<3 ;i++){format += r.nextInt(10);}//实例化一个JerseyClient client = new Client();//保存数据库path = "upload/fujian/"+ format + "." + ext;//另一台服务器的请求路径是?String url = Constants.IMAGE_URL  + path;//设置请求路径WebResource resource = client.resource(url);//发送开始  POST  GET   PUTtry {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服务是否启动。");}// convertDocumentConverter 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());}}

利用openoffice将上传办公文档转换成PDF或者html相关推荐

  1. ASP.Net中实现上传过程中将文本文件转换成PDF的方法

    iTextSharp是一个常用的PDF库,我们可以使用它来创建.修改PDF文件或对PDF文件进行一些其他额外的操作.本文讲述了如何在上传过程中将文本文件转换成PDF的方法. 基本工作 在开始之前,我们 ...

  2. 上传Text文档并转换为PDF(解决乱码)

    前些日子,Insus.NET有分享一篇<上传Text文档并转换为PDF>http://www.cnblogs.com/insus/p/4313092.html 它是按最简单与默认方式来处理 ...

  3. word转图片 java_Java 利用LibreOffice将Office文档转换成 PDF,进而转图片,实现在线预览功能...

    项目中需要将 Office 文档上传并实现在线预览,用到了 LibreOffice 将 Office 文档转换为 PDF 文档,然后再用 pdfbox 将 PDF 转为图片. 本文介绍借助 Libre ...

  4. C# 上传WPS Excel 后台转换成txt,再压缩为ZIP

    一开始在读取ET文件的时候用的是etapi.dll自带插件,发现调试时会报各种各样的拒绝访问的错误,创建txt文件报[对路径"c:\\windows\\system32\\inetsrv\\ ...

  5. 文件上传至将File转换成MultiPartFile

    在文件上传业务上需要将文件上传至将File转换成MultiPartFile的时候,我搜索得到采用MockMultipartFile这个类可以轻松的转换. 但是,当我准备使用的时候,坑出现了.它是spr ...

  6. vue-tinymce的使用,粘贴文件上传,自定义文件上传,改base64转换成上传到服务器返回url

    vue-tinymce的使用,粘贴文件上传,自定义文件上传,改base64转换成上传到服务器返回url vue中使用 <vue-tinymcev-model="itemForm.con ...

  7. Office文档转换成PDF

    分享知识 传递快乐 Office文档转换成PDF 文档转换的方式有很多种,比如有Apache下的POI.jodconverter等技术.本例用的jodconverter-core-3.0技术对文档进行 ...

  8. WORD文档转换成PDF格式

    由于一个客户的项目中需要将WORD文档转换成PDF格式,实战教程如下: 需求分析:客户的项目以B/S结构为主,提供一个WORD文件在后台自动转换成PDF,经过实际 测试, 如果该篇WORD文档有100 ...

  9. 怎么把word文档转换成PDF?

    Word文件完成编辑之后,想要转发给他人,但是担心在转发过程中出现了格式错乱的情况,将word文档转换成PDF格式再转发就可以避免类似情况了.那么如何将word文档转换成PDF文件? 方法一: 在编辑 ...

最新文章

  1. 记一次shell脚本推后台stopped的问题
  2. ERP成功全球实施十大成功案例
  3. TCP 客户端程序开发
  4. 中国联通李福昌:探索无线连接的未来
  5. c++自定义的数据库类
  6. hdu (欧拉函数+容斥原理) GCD
  7. 手把手带你玩转Tensorflow 物体检测 API (1)——运行实例
  8. 血栓清道夫机器人_血栓“清道夫”找到了!木耳排第三,排在第一很多人都并不知道...
  9. 将任何变量的值进行二进制输出的方法
  10. C语言学习笔记---动态内存分配
  11. 医学专业失业率最高 三类相关行业人才紧缺
  12. 【BZOJ2095】[Poi2010]Bridges 动态加边网络流
  13. android 多线程互斥,Android同步类:Mutex和Condition
  14. OpenCV读写视频(编解码器)
  15. 关于贝叶斯公式的解释,通俗易懂(转载)
  16. 《嵌入式C编程:PIC单片机和C编程技术与应用》一导读
  17. 高精度姿态传感器LPMS-NAV3系列
  18. html 链接excel,如何把excel表格中的文本链接变成可点击打开的网址链接(超链接)?...
  19. 基于 MySQL Binlog 的 Elasticsearch 数据同步实践 原
  20. MODIS NDVI下载处理 MOD13A1, win10

热门文章

  1. python算法工程师书籍_我是如何成为算法工程师的,超详细的学习路线
  2. 一条短信被骗走53万
  3. 投sci论文计算机类,计算机类的SCI期刊如何准备
  4. 如何建一个STM32F030工程模板(标准库版)
  5. 百度地图保存图片_百度地图与高德地图PK,你pick哪一个?
  6. C语言编写程序,输入三角形的三条边长,求三角形的面积。设输入的三条边长a、b、c能构成三角形。
  7. rcu锁原理以及rcu example学习
  8. 【Excel-Vlookup】基础篇
  9. html中表格布局还是div布局,表格布局和css div布局
  10. WEB网页设计期末作业个人主页——基于HTML+CSS制作个人简介网站