赞
踩
https://www.openoffice.org/download/https://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
回车
1.引入依赖
- <dependency>
- <groupId>com.artofsolving</groupId>
- <artifactId>jodconverter</artifactId>
- <version>2.2.1</version>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.7</version>
- </dependency>
2.编写文件格式转换工具类
- package com.lzl.util;
-
- import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
- import com.artofsolving.jodconverter.DocumentConverter;
- import com.artofsolving.jodconverter.DocumentFormat;
- import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
- import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
- import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
-
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
-
- /**
- * 文件格式转换工具类
- */
- public class FileConvertUtil {
-
- /**
- * 默认转换后文件后缀
- */
- private static final String DEFAULT_SUFFIX = "pdf";
- /**
- * openoffice_port
- */
- private static final Integer OPENOFFICE_PORT = 8100;
-
- /**
- * 方法描述 office文档转换为PDF(处理本地文件)
- * @param sourcePath 源文件路径
- * @param suffix 源文件后缀
- * @return InputStream 转换后文件输入流
- */
- public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
- File inputFile = new File(sourcePath);
- InputStream inputStream = new FileInputStream(inputFile);
- return covertCommonByStream(inputStream, suffix);
- }
-
- /**
- * 方法描述 office文档转换为PDF(处理网络文件)
- * @param netFileUrl 网络文件路径
- * @param suffix 文件后缀
- * @return InputStream 转换后文件输入流
- */
- public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
- // 创建URL
- URL url = new URL(netFileUrl);
- // 试图连接并取得返回状态码
- URLConnection urlconn = url.openConnection();
- urlconn.connect();
- HttpURLConnection httpconn = (HttpURLConnection) urlconn;
- int httpResult = httpconn.getResponseCode();
- if (httpResult == HttpURLConnection.HTTP_OK) {
- InputStream inputStream = urlconn.getInputStream();
- return covertCommonByStream(inputStream, suffix);
- }
- return null;
- }
-
- /**
- * 方法描述 将文件以流的形式转换
- *
- * @param inputStream 源文件输入流
- * @param suffix 源文件后缀
- * @return InputStream 转换后文件输入流
- */
- public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
- connection.connect();
- DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
- DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
- DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
- DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
- converter.convert(inputStream, sourceFormat, out, targetFormat);
- connection.disconnect();
- return outputStreamConvertInputStream(out);
- }
-
- /**
- * 方法描述 outputStream转inputStream
- */
- public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
- ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
- return new ByteArrayInputStream(baos.toByteArray());
- }
-
- }
3.编写工具类
- package com.lzl.util;
-
- import org.apache.commons.lang3.StringUtils;
-
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
-
- public class SmartStringUtil extends StringUtils {
-
- // ===============split =======================
-
- public static Set<String> splitConvertToSet(String str, String split) {
- if (isEmpty(str)) {
- return new HashSet<String>();
- }
- String[] splitArr = str.split(split);
- HashSet<String> set = new HashSet<String>(splitArr.length);
- for (String string : splitArr) {
- set.add(string);
- }
- return set;
- }
-
- public static List<String> splitConvertToList(String str, String split) {
- if (isEmpty(str)) {
- return new ArrayList<String>();
- }
- String[] splitArr = str.split(split);
- ArrayList<String> list = new ArrayList<String>(splitArr.length);
- for (String string : splitArr) {
- list.add(string);
- }
- return list;
- }
-
- // ===============split Integer=======================
-
- public static List<Integer> splitConverToIntList(String str, String split, int defaultVal) {
- if (isEmpty(str)) {
- return new ArrayList<Integer>();
- }
- String[] strArr = str.split(split);
- List<Integer> list = new ArrayList<Integer>(strArr.length);
- for (int i = 0; i < strArr.length; i++) {
- try {
- int parseInt = Integer.parseInt(strArr[i]);
- list.add(parseInt);
- } catch (NumberFormatException e) {
- list.add(defaultVal);
- continue;
- }
- }
- return list;
- }
-
- public static Set<Integer> splitConverToIntSet(String str, String split, int defaultVal) {
- if (isEmpty(str)) {
- return new HashSet<Integer>();
- }
- String[] strArr = str.split(split);
- HashSet<Integer> set = new HashSet<Integer>(strArr.length);
- for (int i = 0; i < strArr.length; i++) {
- try {
- int parseInt = Integer.parseInt(strArr[i]);
- set.add(parseInt);
- } catch (NumberFormatException e) {
- set.add(defaultVal);
- continue;
- }
- }
- return set;
- }
-
- public static Set<Integer> splitConverToIntSet(String str, String split) {
- return splitConverToIntSet(str, split, 0);
- }
-
- public static List<Integer> splitConverToIntList(String str, String split) {
- return splitConverToIntList(str, split, 0);
- }
-
- public static int[] splitConvertToIntArray(String str, String split, int defaultVal) {
- if (isEmpty(str)) {
- return new int[0];
- }
- String[] strArr = str.split(split);
- int[] result = new int[strArr.length];
- for (int i = 0; i < strArr.length; i++) {
- try {
- result[i] = Integer.parseInt(strArr[i]);
- } catch (NumberFormatException e) {
- result[i] = defaultVal;
- continue;
- }
- }
- return result;
- }
-
- public static int[] splitConvertToIntArray(String str, String split) {
- return splitConvertToIntArray(str, split, 0);
- }
-
- // ===============split 2 Long=======================
-
- public static List<Long> splitConverToLongList(String str, String split, long defaultVal) {
- if (isEmpty(str)) {
- return new ArrayList<Long>();
- }
- String[] strArr = str.split(split);
- List<Long> list = new ArrayList<Long>(strArr.length);
- for (int i = 0; i < strArr.length; i++) {
- try {
- long parseLong = Long.parseLong(strArr[i]);
- list.add(parseLong);
- } catch (NumberFormatException e) {
- list.add(defaultVal);
- continue;
- }
- }
- return list;
- }
-
- public static List<Long> splitConverToLongList(String str, String split) {
- return splitConverToLongList(str, split, 0L);
- }
-
- public static long[] splitConvertToLongArray(String str, String split, long defaultVal) {
- if (isEmpty(str)) {
- return new long[0];
- }
- String[] strArr = str.split(split);
- long[] result = new long[strArr.length];
- for (int i = 0; i < strArr.length; i++) {
- try {
- result[i] = Long.parseLong(strArr[i]);
- } catch (NumberFormatException e) {
- result[i] = defaultVal;
- continue;
- }
- }
- return result;
- }
-
- public static long[] splitConvertToLongArray(String str, String split) {
- return splitConvertToLongArray(str, split, 0L);
- }
-
- // ===============split convert byte=======================
-
- public static List<Byte> splitConverToByteList(String str, String split, byte defaultVal) {
- if (isEmpty(str)) {
- return new ArrayList<Byte>();
- }
- String[] strArr = str.split(split);
- List<Byte> list = new ArrayList<Byte>(strArr.length);
- for (int i = 0; i < strArr.length; i++) {
- try {
- byte parseByte = Byte.parseByte(strArr[i]);
- list.add(parseByte);
- } catch (NumberFormatException e) {
- list.add(defaultVal);
- continue;
- }
- }
- return list;
- }
-
- public static List<Byte> splitConverToByteList(String str, String split) {
- return splitConverToByteList(str, split, (byte) 0);
- }
-
- public static byte[] splitConvertToByteArray(String str, String split, byte defaultVal) {
- if (isEmpty(str)) {
- return new byte[0];
- }
- String[] strArr = str.split(split);
- byte[] result = new byte[strArr.length];
- for (int i = 0; i < strArr.length; i++) {
- try {
- result[i] = Byte.parseByte(strArr[i]);
- } catch (NumberFormatException e) {
- result[i] = defaultVal;
- continue;
- }
- }
- return result;
- }
-
- public static byte[] splitConvertToByteArray(String str, String split) {
- return splitConvertToByteArray(str, split, (byte) 0);
- }
-
- // ===============split convert double=======================
-
- public static List<Double> splitConverToDoubleList(String str, String split, double defaultVal) {
- if (isEmpty(str)) {
- return new ArrayList<Double>();
- }
- String[] strArr = str.split(split);
- List<Double> list = new ArrayList<Double>(strArr.length);
- for (int i = 0; i < strArr.length; i++) {
- try {
- double parseByte = Double.parseDouble(strArr[i]);
- list.add(parseByte);
- } catch (NumberFormatException e) {
- list.add(defaultVal);
- continue;
- }
- }
- return list;
- }
-
- public static List<Double> splitConverToDoubleList(String str, String split) {
- return splitConverToDoubleList(str, split, 0);
- }
-
- public static double[] splitConvertToDoubleArray(String str, String split, double defaultVal) {
- if (isEmpty(str)) {
- return new double[0];
- }
- String[] strArr = str.split(split);
- double[] result = new double[strArr.length];
- for (int i = 0; i < strArr.length; i++) {
- try {
- result[i] = Double.parseDouble(strArr[i]);
- } catch (NumberFormatException e) {
- result[i] = defaultVal;
- continue;
- }
- }
- return result;
- }
-
- public static double[] splitConvertToDoubleArray(String str, String split) {
- return splitConvertToDoubleArray(str, split, 0);
- }
-
- // ===============solit convert float=======================
-
- public static List<Float> splitConverToFloatList(String str, String split, float defaultVal) {
- if (isEmpty(str)) {
- return new ArrayList<Float>();
- }
- String[] strArr = str.split(split);
- List<Float> list = new ArrayList<Float>(strArr.length);
- for (int i = 0; i < strArr.length; i++) {
- try {
- float parseByte = Float.parseFloat(strArr[i]);
- list.add(parseByte);
- } catch (NumberFormatException e) {
- list.add(defaultVal);
- continue;
- }
- }
- return list;
- }
-
- public static List<Float> splitConverToFloatList(String str, String split) {
- return splitConverToFloatList(str, split, 0f);
- }
-
- public static float[] splitConvertToFloatArray(String str, String split, float defaultVal) {
- if (isEmpty(str)) {
- return new float[0];
- }
- String[] strArr = str.split(split);
- float[] result = new float[strArr.length];
- for (int i = 0; i < strArr.length; i++) {
- try {
- result[i] = Float.parseFloat(strArr[i]);
- } catch (NumberFormatException e) {
- result[i] = defaultVal;
- continue;
- }
- }
- return result;
- }
-
- public static float[] splitConvertToFloatArray(String str, String split) {
- return splitConvertToFloatArray(str, split, 0f);
- }
-
- // ===============upperCase=======================
-
- /**
- * 将首字母大写
- *
- * @param str
- * @return
- */
- public static String upperCaseFirstChar(String str) {
- if (str == null || str.isEmpty()) {
- return str;
- }
- char firstChar = str.charAt(0);
- if (Character.isUpperCase(firstChar)) {
- return str;
- }
- char[] values = str.toCharArray();
- values[0] = Character.toUpperCase(firstChar);
- return new String(values);
- }
-
- }
4.编写controller
- package com.lzl.controller;
-
- import com.lzl.service.OnlinePreviewService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletResponse;
-
- @RestController
- public class OnlinePreviewController {
-
- @Autowired
- private OnlinePreviewService onlinePreviewService;
-
- @GetMapping("/onlinePreview")
- public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
- onlinePreviewService.onlinePreview(url,response);
- }
- }
5.编写serivce和service实现类
- package com.lzl.service;
-
- import javax.servlet.http.HttpServletResponse;
-
- public interface OnlinePreviewService {
-
- void onlinePreview(String url, HttpServletResponse response) throws Exception;
- }
- package com.lzl.service.impl;
-
- import com.lzl.service.OnlinePreviewService;
- import com.lzl.util.FileConvertUtil;
- import com.lzl.util.SmartStringUtil;
- import org.springframework.stereotype.Service;
-
- import javax.servlet.http.HttpServletResponse;
- import java.io.InputStream;
- import java.io.OutputStream;
-
- @Service
- public class OnlinePreviewServiceImpl implements OnlinePreviewService {
-
- @Override
- public void onlinePreview(String url, HttpServletResponse response) throws Exception {
- //获取文件类型
- String[] str = SmartStringUtil.split(url, "\\.");
-
- if (str.length == 0) {
- throw new Exception("文件格式不正确");
- }
- String suffix = str[str.length - 1];
- if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
- && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")) {
- throw new Exception("文件格式不支持预览");
- }
- InputStream in = FileConvertUtil.convertLocaleFile(url, suffix);
- OutputStream outputStream = response.getOutputStream();
- //创建存放文件内容的数组
- byte[] buff = new byte[1024];
- //所读取的内容使用n来接收
- int n;
- //当没有读取完时,继续读取,循环
- while ((n = in.read(buff)) != -1) {
- //将字节数组的数据全部写入到输出流中
- outputStream.write(buff, 0, n);
- }
- //强制将缓存区的数据进行输出
- outputStream.flush();
- //关流
- outputStream.close();
- in.close();
- }
- }
启动项目测试
报错
- java.lang.IllegalArgumentException: inputFormat is null
- at com.artofsolving.jodconverter.openoffice.converter.AbstractOpenOfficeDocumentConverter.ensureNotNull(AbstractOpenOfficeDocumentConverter.java:113) ~[jodconverter-2.2.1.jar:na]
- at com.artofsolving.jodconverter.openoffice.converter.AbstractOpenOfficeDocumentConverter.convert(AbstractOpenOfficeDocumentConverter.java:79) ~[jodconverter-2.2.1.jar:na]
- at com.lzl.util.FileConvertUtil.covertCommonByStream(FileConvertUtil.java:77) ~[classes/:na]
- at com.lzl.util.FileConvertUtil.convertLocaleFile(FileConvertUtil.java:38) ~[classes/:na]
解决办法:
新建com.artofsolving.jodconverter包重写BasicDocumentFormatRegistry类
- package com.artofsolving.jodconverter;
-
- import com.artofsolving.jodconverter.DocumentFormat;
- import com.artofsolving.jodconverter.DocumentFormatRegistry;
-
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
-
- /**
- *
- * @description: 重写 BasicDocumentFormatRegistry 文档格式
- *
- */
- public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
-
- private List/* <DocumentFormat> */ documentFormats = new ArrayList();
-
- public void addDocumentFormat(DocumentFormat documentFormat) {
- documentFormats.add(documentFormat);
- }
-
- protected List/* <DocumentFormat> */ getDocumentFormats() {
- return documentFormats;
- }
-
-
- @Override
- public DocumentFormat getFormatByFileExtension(String extension) {
- if (extension == null) {
- return null;
- }
-
- //将文件名后缀统一转化
- if (extension.indexOf("doc") >= 0) {
- extension = "doc";
- }
- if (extension.indexOf("ppt") >= 0) {
- extension = "ppt";
- }
- if (extension.indexOf("xls") >= 0) {
- extension = "xls";
- }
- String lowerExtension = extension.toLowerCase();
- for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
- DocumentFormat format = (DocumentFormat) it.next();
- if (format.getFileExtension().equals(lowerExtension)) {
- return format;
- }
- }
- return null;
- }
-
- @Override
- public DocumentFormat getFormatByMimeType(String mimeType) {
- for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
- DocumentFormat format = (DocumentFormat) it.next();
- if (format.getMimeType().equals(mimeType)) {
- return format;
- }
- }
- return null;
- }
- }
重新启动项目 测试:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。