java项目中利用OpenOffice实现预览

项目文件转为PDF实现预览

openoffice实现预览还是相对简单的,但是也需要注意一些事项,看了一些贴,有的没有提示这些,就一起说说。

核心jar包

看了不少帖子,引用的也不一样,使用后我采用的这两个,其他IO包都会涉及。

<!-- 利用openoffice文件转为PDF -->
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>19.0</version>
		</dependency>
		<dependency>
			<groupId>com.github.livesense</groupId>
			<artifactId>jodconverter-core</artifactId>
			<version>1.0.5</version>
		</dependency>

工具类

工具类有很多种,也是根据不同的需求,有的转成HTML、PDF等等。对于服务的调用也不尽相同。我是直接代码调用服务,没有服务时候打开服务。代码中的安装位置是默认的,根据实际修改,注意版本问题

package net.cnki.util;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.ExternalOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeException;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author ZhiPengyu
 * @ClassName:    [OpenofficeUtil]
 * @Description:  [调用openoffice服务,进行文件预览]
 * 在程序安装目录下执行以下启动服务:soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard & 
 * @CreateDate:   [2019年10月8日 下午3:21:06]
 */
public class OpenofficeUtil {
	static Logger logger = LoggerFactory.getLogger(OpenofficeUtil.class);
	private static String officeHome = getOfficeHome();
	private static int port = 8100;// 这里的内容是根据你的系统选择不同的端口号,windows系统的端口号是8100
	private static OfficeManager officeManager; // 尝试连接已存在的服务器
												
	// openoffice的安装地址
	private static String getOfficeHome() {
		String osName = System.getProperty("os.name");
		if (Pattern.matches("Linux.*", osName)) {
			return "/opt/openoffice4";
		} else if (Pattern.matches("Windows.*", osName)) {
			return "C:/Program Files (x86)/OpenOffice 4";
		} else if (Pattern.matches("Mac.*", osName)) {
			return "/Application/OpenOffice.org.app/Contents";
		}
		return null;
	}

	private static boolean reconnect() {
		try {
			// 尝试连接openoffice的已存在的服务器
			ExternalOfficeManagerConfiguration externalProcessOfficeManager = new ExternalOfficeManagerConfiguration();
			externalProcessOfficeManager.setConnectOnStart(true);
			externalProcessOfficeManager.setPortNumber(8100);
			officeManager = externalProcessOfficeManager.buildOfficeManager();
			officeManager.start();
			return true;
		} catch (OfficeException e) {
			e.printStackTrace();
			return false;
		}

	}

// 开启新的openoffice的进程
	private static void start() {
		logger.debug("启动OpenOffice服务");
		try {
			DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
			configuration.setOfficeHome(officeHome);// 安装地址
			configuration.setPortNumbers(port);// 端口号
			configuration.setTaskExecutionTimeout(1000 * 60 * 5);// 设置任务执行超时为5分钟
			configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24);// 设置任务队列超时为24小时
			officeManager = configuration.buildOfficeManager();
			officeManager.start(); // 启动服务
		} catch (Exception e) {
			logger.error("启动OpenOffice服务出错" + e);
		}
	}

// 使用完需要关闭该进程
	private static void stop() {
		logger.debug("关闭OpenOffice服务");
		try {
			if (officeManager != null)
				officeManager.stop();
		} catch (Exception e) {
			logger.error("关闭OpenOffice服务出错" + e);
		}
	}

	/**
	 * 转换入口
	 * @param inputFilePath 转换前文件全路径
	 * @param outputFilePath 转换后文件全路径
	 * @return
	 */
	public static Map<String, Object> convertToPdf(String inputFilePath, String outputFilePath) {
		Map<String, Object> tResultMap = new HashMap<>();
		tResultMap.put("status", "fail");
		long begin_time = new Date().getTime();
		File inputFile = null;
		File outFile = null;
		try { // 如果已存在的服务不能连接或者不存在服务,那么开启新的服务
			if (!reconnect()) {
				start();// 开启服务
			}
			inputFile = new File(inputFilePath);
			outFile = new File(outputFilePath);
			logger.info("开始转换文档:" + inputFilePath + "=>" + outputFilePath);
			OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
			converter.convert(inputFile, outFile); // 转换文档
			long end_time = new Date().getTime();
			logger.info("文件转换耗时:[" + (end_time - begin_time) + "]ms");
		} catch (Exception e) {
			logger.error("转换文档出错" + e);
			outFile = null;
		} finally {
			logger.info("结束转换文档");
			stop();
		}
		tResultMap.put("result", outputFilePath);
		tResultMap.put("status", "success");
		return tResultMap;
	}

	// 测试工具类是否成功
	/*
	 * public static void main(String[] args) { File sf = PdfUtils.convertToPdf(
	 * "C:\\Users\\Administrator\\Desktop\\TestFile\\singleFile\\立项论证报告书-中国海油科技情报收集及共享应用研究.docx"
	 * ); //File sf = new File("E:/test.ppt"); System.out.println(sf.getPath()); }
	 */

}

controller层调用

以下代码我加入了异常拦截、参数加密,都不用管。直接调用工具类就行。前台用的a标签,跳转新页,url会有参数明文,看个人处理吧。已转换的就直接用就行

@RequestMapping("/fileview")
	public void fileview(String filePdf,HttpServletRequest request, HttpServletResponse response) throws IOException, PreviewException  {
		//String materialId = request.getParameter("materialId");
		logger.info("文件预览功能!");
		if(ParametersUtil.isBlank(filePdf)) {
			throw new PreviewException("预览文件未找到!");
		}
		byte[] decodedBytes = Base64.getDecoder().decode(filePdf);
		String decodedString = new String(decodedBytes, Charset.defaultCharset());
		int materialid = Integer.valueOf(decodedString);
		ProjectMaterial mateProject = projectMaterialService.selectByPrimaryKey(materialid);
		if(mateProject == null) {
			throw new PreviewException("预览文件未找到!");
		}
		String inputFilePath = mateProject.getMaterialPath();
		String[] extensions = inputFilePath.split("\\.");
		String extension = extensions[extensions.length - 1].toLowerCase();//并转为小写
		Map<String, Object> mapData= new HashMap<>();
				
		if("pdf".equals(extension)) {
			mapData.put("status", "success");
			mapData.put("result", inputFilePath);
		}else {
			File file = new File(fileEntity.getFileToPdfPath());
			if (!file.exists()) {
				file.mkdirs();
			}
			File file1 = new File(inputFilePath);
			if(!file1.exists()) {
				throw new PreviewException("预览文件未找到!");
			}
			//去掉拓展名
			String fileanmes = file1.getName().substring(0, file1.getName().lastIndexOf("."));
			String outputFilePath = fileEntity.getFileToPdfPath()+fileanmes+"_"+extension+".pdf";
			File checkFile = new File(outputFilePath);
			if (checkFile.exists()) {
				mapData.put("status", "success");
				mapData.put("result", outputFilePath);
			}else {
				//mapData= ConverterUtil.openOfficeToPDF(inputFilePath, outputFilePath);
				mapData = OpenofficeUtil.convertToPdf(inputFilePath, outputFilePath);
			}
		}
		//得到id,查库获取文件名称
		InputStream input = null;
		OutputStream out = null;
		
		String status = (String) mapData.get("status");
		String filePath = "";
		if("success".equals(status)) {
			filePath = (String) mapData.get("result");
		}else {
			filePath="";
		}
		
		File file = new File(filePath);
		try {
			input = new FileInputStream(file);
			response.setContentType("application/pdf");
			out = response.getOutputStream();

			byte[] b = new byte[512];
			if (out != null) {
				if (input != null) {
					while ((input.read(b)) != -1) {
						out.write(b);
					}
				}
			}

			out.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.toString());
		}finally {
			input.close();
			out.close();
		}
		
		
	}

问题总结

1、调用转换的效率问题

之前采用代码打开服务并不指定端口的方式执行起来效率会很慢,十几秒才转换完。因此,建议指定端口并提前开启服务,会快很多,用户体验也很好

2、启动服务的问题

启动时,不论是否后台开启服务,看你的命令是否在安装目录下,没有在目录下的话,命令前要写好安装位置。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在信号处理领域,DOA(Direction of Arrival)估计是一项关键技术,主要用于确定多个信号源到达接收阵列的方向。本文将详细探讨三种ESPRIT(Estimation of Signal Parameters via Rotational Invariance Techniques)算法在DOA估计实现,以及它们在MATLAB环境的具体应用。 ESPRIT算法是由Paul Kailath等人于1986年提出的,其核心思想是利用阵列数据的旋不变性来估计信号源的角度。这种算法相比传统的 MUSIC(Multiple Signal Classification)算法具有较低的计算复杂度,且无需进行特征值分解,因此在实际应用颇具优势。 1. 普通ESPRIT算法 普通ESPRIT算法分为两个主要步骤:构造等效旋不变系统和估计角度。通过空间平移(如延时)构建两个子阵列,使得它们之间的关系具有旋不变性。然后,通过对子阵列数据进行最小二乘拟合,可以得到信号源的角频率估计,进一步换为DOA估计。 2. 常规ESPRIT算法实现 在描述提到的`common_esprit_method1.m`和`common_esprit_method2.m`是两种不同的普通ESPRIT算法实现。它们可能在实现细节上略有差异,比如选择子阵列的方式、参数估计的策略等。MATLAB代码通常会包含预处理步骤(如数据归一化)、子阵列构造、旋不变性矩阵的建立、最小二乘估计等部分。通过运行这两个文件,可以比较它们在估计精度和计算效率上的异同。 3. TLS_ESPRIT算法 TLS(Total Least Squares)ESPRIT是对普通ESPRIT的优化,它考虑了数据噪声的影响,提高了估计的稳健性。在TLS_ESPRIT算法,不假设数据噪声是高斯白噪声,而是采用总最小二乘准则来拟合数据。这使得算法在噪声环境下表现更优。`TLS_esprit.m`文件应该包含了TLS_ESPRIT算法的完整实现,包括TLS估计的步骤和旋不变性矩阵的改进处理。 在实际应用,选择合适的ESPRIT变体取决于系统条件,例如噪声水平、信号质量以及计算资源。通过MATLAB实现,研究者和工程师可以方便地比较不同算法的效果,并根据需要进行调整和优化。同时,这些代码也为教学和学习DOA估计提供了一个直观的平台,有助于深入理解ESPRIT算法的工作原理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值