当前位置:   article > 正文

Springboot整合openoffice实现文件在线预览_openoffice 在线预览

openoffice 在线预览

一 下载安装openoffice

https://www.openoffice.org/download/icon-default.png?t=N7T8https://www.openoffice.org/download/

我这里使用4.1.10 windows版本 

下载完后启动服务

运行→cmd,输入:

cd C:\Program Files (x86)\OpenOffice 4\program

回车

再输入

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

回车

二 springboot整合

1.引入依赖

  1. <dependency>
  2. <groupId>com.artofsolving</groupId>
  3. <artifactId>jodconverter</artifactId>
  4. <version>2.2.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.commons</groupId>
  8. <artifactId>commons-lang3</artifactId>
  9. <version>3.7</version>
  10. </dependency>

2.编写文件格式转换工具类

  1. package com.lzl.util;
  2. import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
  3. import com.artofsolving.jodconverter.DocumentConverter;
  4. import com.artofsolving.jodconverter.DocumentFormat;
  5. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
  6. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
  7. import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
  8. import java.io.*;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. import java.net.URLConnection;
  12. /**
  13. * 文件格式转换工具类
  14. */
  15. public class FileConvertUtil {
  16. /**
  17. * 默认转换后文件后缀
  18. */
  19. private static final String DEFAULT_SUFFIX = "pdf";
  20. /**
  21. * openoffice_port
  22. */
  23. private static final Integer OPENOFFICE_PORT = 8100;
  24. /**
  25. * 方法描述 office文档转换为PDF(处理本地文件)
  26. * @param sourcePath 源文件路径
  27. * @param suffix 源文件后缀
  28. * @return InputStream 转换后文件输入流
  29. */
  30. public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
  31. File inputFile = new File(sourcePath);
  32. InputStream inputStream = new FileInputStream(inputFile);
  33. return covertCommonByStream(inputStream, suffix);
  34. }
  35. /**
  36. * 方法描述 office文档转换为PDF(处理网络文件)
  37. * @param netFileUrl 网络文件路径
  38. * @param suffix 文件后缀
  39. * @return InputStream 转换后文件输入流
  40. */
  41. public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
  42. // 创建URL
  43. URL url = new URL(netFileUrl);
  44. // 试图连接并取得返回状态码
  45. URLConnection urlconn = url.openConnection();
  46. urlconn.connect();
  47. HttpURLConnection httpconn = (HttpURLConnection) urlconn;
  48. int httpResult = httpconn.getResponseCode();
  49. if (httpResult == HttpURLConnection.HTTP_OK) {
  50. InputStream inputStream = urlconn.getInputStream();
  51. return covertCommonByStream(inputStream, suffix);
  52. }
  53. return null;
  54. }
  55. /**
  56. * 方法描述 将文件以流的形式转换
  57. *
  58. * @param inputStream 源文件输入流
  59. * @param suffix 源文件后缀
  60. * @return InputStream 转换后文件输入流
  61. */
  62. public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
  63. ByteArrayOutputStream out = new ByteArrayOutputStream();
  64. OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
  65. connection.connect();
  66. DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
  67. DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
  68. DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
  69. DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
  70. converter.convert(inputStream, sourceFormat, out, targetFormat);
  71. connection.disconnect();
  72. return outputStreamConvertInputStream(out);
  73. }
  74. /**
  75. * 方法描述 outputStream转inputStream
  76. */
  77. public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
  78. ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
  79. return new ByteArrayInputStream(baos.toByteArray());
  80. }
  81. }

3.编写工具类

  1. package com.lzl.util;
  2. import org.apache.commons.lang3.StringUtils;
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7. public class SmartStringUtil extends StringUtils {
  8. // ===============split =======================
  9. public static Set<String> splitConvertToSet(String str, String split) {
  10. if (isEmpty(str)) {
  11. return new HashSet<String>();
  12. }
  13. String[] splitArr = str.split(split);
  14. HashSet<String> set = new HashSet<String>(splitArr.length);
  15. for (String string : splitArr) {
  16. set.add(string);
  17. }
  18. return set;
  19. }
  20. public static List<String> splitConvertToList(String str, String split) {
  21. if (isEmpty(str)) {
  22. return new ArrayList<String>();
  23. }
  24. String[] splitArr = str.split(split);
  25. ArrayList<String> list = new ArrayList<String>(splitArr.length);
  26. for (String string : splitArr) {
  27. list.add(string);
  28. }
  29. return list;
  30. }
  31. // ===============split Integer=======================
  32. public static List<Integer> splitConverToIntList(String str, String split, int defaultVal) {
  33. if (isEmpty(str)) {
  34. return new ArrayList<Integer>();
  35. }
  36. String[] strArr = str.split(split);
  37. List<Integer> list = new ArrayList<Integer>(strArr.length);
  38. for (int i = 0; i < strArr.length; i++) {
  39. try {
  40. int parseInt = Integer.parseInt(strArr[i]);
  41. list.add(parseInt);
  42. } catch (NumberFormatException e) {
  43. list.add(defaultVal);
  44. continue;
  45. }
  46. }
  47. return list;
  48. }
  49. public static Set<Integer> splitConverToIntSet(String str, String split, int defaultVal) {
  50. if (isEmpty(str)) {
  51. return new HashSet<Integer>();
  52. }
  53. String[] strArr = str.split(split);
  54. HashSet<Integer> set = new HashSet<Integer>(strArr.length);
  55. for (int i = 0; i < strArr.length; i++) {
  56. try {
  57. int parseInt = Integer.parseInt(strArr[i]);
  58. set.add(parseInt);
  59. } catch (NumberFormatException e) {
  60. set.add(defaultVal);
  61. continue;
  62. }
  63. }
  64. return set;
  65. }
  66. public static Set<Integer> splitConverToIntSet(String str, String split) {
  67. return splitConverToIntSet(str, split, 0);
  68. }
  69. public static List<Integer> splitConverToIntList(String str, String split) {
  70. return splitConverToIntList(str, split, 0);
  71. }
  72. public static int[] splitConvertToIntArray(String str, String split, int defaultVal) {
  73. if (isEmpty(str)) {
  74. return new int[0];
  75. }
  76. String[] strArr = str.split(split);
  77. int[] result = new int[strArr.length];
  78. for (int i = 0; i < strArr.length; i++) {
  79. try {
  80. result[i] = Integer.parseInt(strArr[i]);
  81. } catch (NumberFormatException e) {
  82. result[i] = defaultVal;
  83. continue;
  84. }
  85. }
  86. return result;
  87. }
  88. public static int[] splitConvertToIntArray(String str, String split) {
  89. return splitConvertToIntArray(str, split, 0);
  90. }
  91. // ===============split 2 Long=======================
  92. public static List<Long> splitConverToLongList(String str, String split, long defaultVal) {
  93. if (isEmpty(str)) {
  94. return new ArrayList<Long>();
  95. }
  96. String[] strArr = str.split(split);
  97. List<Long> list = new ArrayList<Long>(strArr.length);
  98. for (int i = 0; i < strArr.length; i++) {
  99. try {
  100. long parseLong = Long.parseLong(strArr[i]);
  101. list.add(parseLong);
  102. } catch (NumberFormatException e) {
  103. list.add(defaultVal);
  104. continue;
  105. }
  106. }
  107. return list;
  108. }
  109. public static List<Long> splitConverToLongList(String str, String split) {
  110. return splitConverToLongList(str, split, 0L);
  111. }
  112. public static long[] splitConvertToLongArray(String str, String split, long defaultVal) {
  113. if (isEmpty(str)) {
  114. return new long[0];
  115. }
  116. String[] strArr = str.split(split);
  117. long[] result = new long[strArr.length];
  118. for (int i = 0; i < strArr.length; i++) {
  119. try {
  120. result[i] = Long.parseLong(strArr[i]);
  121. } catch (NumberFormatException e) {
  122. result[i] = defaultVal;
  123. continue;
  124. }
  125. }
  126. return result;
  127. }
  128. public static long[] splitConvertToLongArray(String str, String split) {
  129. return splitConvertToLongArray(str, split, 0L);
  130. }
  131. // ===============split convert byte=======================
  132. public static List<Byte> splitConverToByteList(String str, String split, byte defaultVal) {
  133. if (isEmpty(str)) {
  134. return new ArrayList<Byte>();
  135. }
  136. String[] strArr = str.split(split);
  137. List<Byte> list = new ArrayList<Byte>(strArr.length);
  138. for (int i = 0; i < strArr.length; i++) {
  139. try {
  140. byte parseByte = Byte.parseByte(strArr[i]);
  141. list.add(parseByte);
  142. } catch (NumberFormatException e) {
  143. list.add(defaultVal);
  144. continue;
  145. }
  146. }
  147. return list;
  148. }
  149. public static List<Byte> splitConverToByteList(String str, String split) {
  150. return splitConverToByteList(str, split, (byte) 0);
  151. }
  152. public static byte[] splitConvertToByteArray(String str, String split, byte defaultVal) {
  153. if (isEmpty(str)) {
  154. return new byte[0];
  155. }
  156. String[] strArr = str.split(split);
  157. byte[] result = new byte[strArr.length];
  158. for (int i = 0; i < strArr.length; i++) {
  159. try {
  160. result[i] = Byte.parseByte(strArr[i]);
  161. } catch (NumberFormatException e) {
  162. result[i] = defaultVal;
  163. continue;
  164. }
  165. }
  166. return result;
  167. }
  168. public static byte[] splitConvertToByteArray(String str, String split) {
  169. return splitConvertToByteArray(str, split, (byte) 0);
  170. }
  171. // ===============split convert double=======================
  172. public static List<Double> splitConverToDoubleList(String str, String split, double defaultVal) {
  173. if (isEmpty(str)) {
  174. return new ArrayList<Double>();
  175. }
  176. String[] strArr = str.split(split);
  177. List<Double> list = new ArrayList<Double>(strArr.length);
  178. for (int i = 0; i < strArr.length; i++) {
  179. try {
  180. double parseByte = Double.parseDouble(strArr[i]);
  181. list.add(parseByte);
  182. } catch (NumberFormatException e) {
  183. list.add(defaultVal);
  184. continue;
  185. }
  186. }
  187. return list;
  188. }
  189. public static List<Double> splitConverToDoubleList(String str, String split) {
  190. return splitConverToDoubleList(str, split, 0);
  191. }
  192. public static double[] splitConvertToDoubleArray(String str, String split, double defaultVal) {
  193. if (isEmpty(str)) {
  194. return new double[0];
  195. }
  196. String[] strArr = str.split(split);
  197. double[] result = new double[strArr.length];
  198. for (int i = 0; i < strArr.length; i++) {
  199. try {
  200. result[i] = Double.parseDouble(strArr[i]);
  201. } catch (NumberFormatException e) {
  202. result[i] = defaultVal;
  203. continue;
  204. }
  205. }
  206. return result;
  207. }
  208. public static double[] splitConvertToDoubleArray(String str, String split) {
  209. return splitConvertToDoubleArray(str, split, 0);
  210. }
  211. // ===============solit convert float=======================
  212. public static List<Float> splitConverToFloatList(String str, String split, float defaultVal) {
  213. if (isEmpty(str)) {
  214. return new ArrayList<Float>();
  215. }
  216. String[] strArr = str.split(split);
  217. List<Float> list = new ArrayList<Float>(strArr.length);
  218. for (int i = 0; i < strArr.length; i++) {
  219. try {
  220. float parseByte = Float.parseFloat(strArr[i]);
  221. list.add(parseByte);
  222. } catch (NumberFormatException e) {
  223. list.add(defaultVal);
  224. continue;
  225. }
  226. }
  227. return list;
  228. }
  229. public static List<Float> splitConverToFloatList(String str, String split) {
  230. return splitConverToFloatList(str, split, 0f);
  231. }
  232. public static float[] splitConvertToFloatArray(String str, String split, float defaultVal) {
  233. if (isEmpty(str)) {
  234. return new float[0];
  235. }
  236. String[] strArr = str.split(split);
  237. float[] result = new float[strArr.length];
  238. for (int i = 0; i < strArr.length; i++) {
  239. try {
  240. result[i] = Float.parseFloat(strArr[i]);
  241. } catch (NumberFormatException e) {
  242. result[i] = defaultVal;
  243. continue;
  244. }
  245. }
  246. return result;
  247. }
  248. public static float[] splitConvertToFloatArray(String str, String split) {
  249. return splitConvertToFloatArray(str, split, 0f);
  250. }
  251. // ===============upperCase=======================
  252. /**
  253. * 将首字母大写
  254. *
  255. * @param str
  256. * @return
  257. */
  258. public static String upperCaseFirstChar(String str) {
  259. if (str == null || str.isEmpty()) {
  260. return str;
  261. }
  262. char firstChar = str.charAt(0);
  263. if (Character.isUpperCase(firstChar)) {
  264. return str;
  265. }
  266. char[] values = str.toCharArray();
  267. values[0] = Character.toUpperCase(firstChar);
  268. return new String(values);
  269. }
  270. }

4.编写controller

  1. package com.lzl.controller;
  2. import com.lzl.service.OnlinePreviewService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import javax.servlet.http.HttpServletResponse;
  8. @RestController
  9. public class OnlinePreviewController {
  10. @Autowired
  11. private OnlinePreviewService onlinePreviewService;
  12. @GetMapping("/onlinePreview")
  13. public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
  14. onlinePreviewService.onlinePreview(url,response);
  15. }
  16. }

5.编写serivce和service实现类

  1. package com.lzl.service;
  2. import javax.servlet.http.HttpServletResponse;
  3. public interface OnlinePreviewService {
  4. void onlinePreview(String url, HttpServletResponse response) throws Exception;
  5. }
  1. package com.lzl.service.impl;
  2. import com.lzl.service.OnlinePreviewService;
  3. import com.lzl.util.FileConvertUtil;
  4. import com.lzl.util.SmartStringUtil;
  5. import org.springframework.stereotype.Service;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. @Service
  10. public class OnlinePreviewServiceImpl implements OnlinePreviewService {
  11. @Override
  12. public void onlinePreview(String url, HttpServletResponse response) throws Exception {
  13. //获取文件类型
  14. String[] str = SmartStringUtil.split(url, "\\.");
  15. if (str.length == 0) {
  16. throw new Exception("文件格式不正确");
  17. }
  18. String suffix = str[str.length - 1];
  19. if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
  20. && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")) {
  21. throw new Exception("文件格式不支持预览");
  22. }
  23. InputStream in = FileConvertUtil.convertLocaleFile(url, suffix);
  24. OutputStream outputStream = response.getOutputStream();
  25. //创建存放文件内容的数组
  26. byte[] buff = new byte[1024];
  27. //所读取的内容使用n来接收
  28. int n;
  29. //当没有读取完时,继续读取,循环
  30. while ((n = in.read(buff)) != -1) {
  31. //将字节数组的数据全部写入到输出流中
  32. outputStream.write(buff, 0, n);
  33. }
  34. //强制将缓存区的数据进行输出
  35. outputStream.flush();
  36. //关流
  37. outputStream.close();
  38. in.close();
  39. }
  40. }

三 测试

启动项目测试

报错

  1. java.lang.IllegalArgumentException: inputFormat is null
  2. at com.artofsolving.jodconverter.openoffice.converter.AbstractOpenOfficeDocumentConverter.ensureNotNull(AbstractOpenOfficeDocumentConverter.java:113) ~[jodconverter-2.2.1.jar:na]
  3. at com.artofsolving.jodconverter.openoffice.converter.AbstractOpenOfficeDocumentConverter.convert(AbstractOpenOfficeDocumentConverter.java:79) ~[jodconverter-2.2.1.jar:na]
  4. at com.lzl.util.FileConvertUtil.covertCommonByStream(FileConvertUtil.java:77) ~[classes/:na]
  5. at com.lzl.util.FileConvertUtil.convertLocaleFile(FileConvertUtil.java:38) ~[classes/:na]

原因是jodconverter 2.2.1 版本不支持docx、xlsx、pptx 转换成PDF格式异常

解决办法:

新建​​com.artofsolving.jodconverter​​​重写​​BasicDocumentFormatRegistry​​

  1. package com.artofsolving.jodconverter​​​;
  2. import com.artofsolving.jodconverter.DocumentFormat;
  3. import com.artofsolving.jodconverter.DocumentFormatRegistry;
  4. import java.util.ArrayList;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. /**
  8. *
  9. * @description: 重写 BasicDocumentFormatRegistry 文档格式
  10. *
  11. */
  12. public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
  13. private List/* <DocumentFormat> */ documentFormats = new ArrayList();
  14. public void addDocumentFormat(DocumentFormat documentFormat) {
  15. documentFormats.add(documentFormat);
  16. }
  17. protected List/* <DocumentFormat> */ getDocumentFormats() {
  18. return documentFormats;
  19. }
  20. @Override
  21. public DocumentFormat getFormatByFileExtension(String extension) {
  22. if (extension == null) {
  23. return null;
  24. }
  25. //将文件名后缀统一转化
  26. if (extension.indexOf("doc") >= 0) {
  27. extension = "doc";
  28. }
  29. if (extension.indexOf("ppt") >= 0) {
  30. extension = "ppt";
  31. }
  32. if (extension.indexOf("xls") >= 0) {
  33. extension = "xls";
  34. }
  35. String lowerExtension = extension.toLowerCase();
  36. for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
  37. DocumentFormat format = (DocumentFormat) it.next();
  38. if (format.getFileExtension().equals(lowerExtension)) {
  39. return format;
  40. }
  41. }
  42. return null;
  43. }
  44. @Override
  45. public DocumentFormat getFormatByMimeType(String mimeType) {
  46. for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
  47. DocumentFormat format = (DocumentFormat) it.next();
  48. if (format.getMimeType().equals(mimeType)) {
  49. return format;
  50. }
  51. }
  52. return null;
  53. }
  54. }

重新启动项目 测试:

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/392956
推荐阅读
相关标签
  

闽ICP备14008679号