使用openoffice,swftools实现office在线预览功能

时间:2019-03-19
本文章向大家介绍使用openoffice,swftools实现office在线预览功能,主要包括使用openoffice,swftools实现office在线预览功能使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
效果:
1.所需软件下载链接
链接: https://pan.baidu.com/s/1JcFL4dM2h2venJ9jLFLIEg 提取码: u4ai 复制这段内容后打开百度网盘手机App,操作更方便哦
 
说明:把两个exe安装包安装,zip解压得到所需的jar包
openoffice安装完成之后,需要双击打开注册,不然会报错
java.net.ConnectException: connection failed: socket,host=10.101.50.71,port=8100,tcpNoDelay=1: java.net.ConnectException: Connection refused: connect
at com.artofsolving.jodconverter.openoffice.connection.AbstractOpenOfficeConnection.connect(AbstractOpenOfficeConnection.java:79)
 
3.软件启动说明

可以通过cmd调用服务, " cd D:/openOffice/install/program" 

执行

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

查看是否安装成功,查看端口对应的pid

    netstat -ano|findstr  8100

 查看pid对应的服务程序名

    tasklist|findstr pid值

也可以把这一步省略,放到java程序中调用服务,因为启动服务占用内存比较大,在java中可以在使用

的时候调用,然后马上销毁。

4.后台核心代码
1).DocConverterUtil
package com.classnet.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;

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;

/**
 * doc docx格式转换
 */
public class DocConverterUtil {
	@SuppressWarnings("unused")
	private String fileString;// (只涉及PDF2swf路径问题)
	@SuppressWarnings("unused")
	private String outputPath = "";// 输入路径 ,如果不设置就输出在默认 的位置
	private String fileName;
	private File pdfFile;
	private File swfFile;
	private File docFile;
	
	// office安装目录
	private static String openOfficeHone = "D:/java/openoffice/program";
	// swftools 安装目录
	private static String swftoolsHome = "D:/java/swftools";

	public DocConverterUtil(String fileString) {
		ini(fileString);
		System.out.println("文件路径" + fileString);
	}

	/**
	 * * 重新设置file
	 * 
	 * @param fileString
	 *            32.
	 */
	public void setFile(String fileString) {
		ini(fileString);
	}

	/**
	 * * 初始化
	 * 
	 * @param fileString
	 * 
	 */
	private void ini(String fileString) {
		this.fileString = fileString;
		fileName = fileString.substring(0, fileString.lastIndexOf("."));
		docFile = new File(fileString);
		pdfFile = new File(fileName + ".pdf");
		swfFile = new File(fileName + ".swf");
	}

	/**
	 * 获取os
	 * 
	 * @return
	 */
	private Integer getOs() {
		String osName = System.getProperty("os.name");
		System.out.println("操作系统名称:" + osName);
		if (Pattern.matches("Linux.*", osName)) {
			return 2;
		} else if (Pattern.matches("Windows.*", osName)) {
			return 1;
		} else if (Pattern.matches("Mac.*", osName)) {
			return 3;
		}
		return null;
	}

	/**
	 * 转为PDF
	 * 
	 * @param file
	 * 
	 */
	private void doc2pdf() throws Exception {
		if (docFile.exists()) {
			if (!pdfFile.exists()) {
				// 调用openoffice服务线程
				String command = openOfficeHone + "/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard";
				Process p = Runtime.getRuntime().exec(command);
				// 连接openoffice服务
				OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
				try {
					connection.connect();
					DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
					converter.convert(docFile, pdfFile);
					// close the connection
					connection.disconnect();
					// 关闭进程
					p.destroy();
					System.out.println("****pdf转换成功,PDF输出: " + pdfFile.getPath() + "****");
				} catch (java.net.ConnectException e) {
					e.printStackTrace();
					System.out.println("****swf转换器异常,openoffice 服务未启动!****");
					throw e;
				} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
					e.printStackTrace();
					System.out.println("****swf转换器异常,读取转换文件 失败****");
					throw e;
				} catch (Exception e) {
					e.printStackTrace();
					throw e;
				}
			} else {
				System.out.println("****已经转换为pdf,不需要再进行转化 ****");
			}
		} else {
			System.out.println("****swf转换器异常,需要转换的文档不存在, 无法转换****");
		}
	}

	/** * 转换成 swf */
	private void pdf2swf() throws Exception {
		Runtime r = Runtime.getRuntime();
		if (!swfFile.exists()) {
			if (pdfFile.exists()) {
				if (getOs() == 1) {// windows环境处理
					try {
						Process p = r
								.exec(swftoolsHome + "/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
						System.out.print(loadStream(p.getInputStream()));
						System.err.print(loadStream(p.getErrorStream()));
						System.out.print(loadStream(p.getInputStream()));
						System.err.println("****swf转换成功,文件输出: " + swfFile.getPath() + "****");
						if (pdfFile.exists()) {
							pdfFile.delete();
						}
					} catch (IOException e) {
						e.printStackTrace();
						throw e;
					}
				} else if (getOs() == 2) {// linux环境处理
					try {
						Process p = r.exec("pdf2swf" + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
						System.out.print(loadStream(p.getInputStream()));
						System.err.print(loadStream(p.getErrorStream()));
						System.err.println("****swf转换成功,文件输出: " + swfFile.getPath() + "****");
						if (pdfFile.exists()) {
							pdfFile.delete();
						}
					} catch (Exception e) {
						e.printStackTrace();
						throw e;
					}
				}
			} else {
				System.out.println("****pdf不存在,无法转换****");
			}
		} else {
			System.out.println("****swf已经存在不需要转换****");
		}
	}

	static String loadStream(InputStream in) throws IOException {
		int ptr = 0;
		in = new BufferedInputStream(in);
		StringBuffer buffer = new StringBuffer();
		while ((ptr = in.read()) != -1) {
			buffer.append((char) ptr);
		}
		return buffer.toString();
	}

	/**
	 * * 转换主方法
	 */
	public boolean conver() {
		if (swfFile.exists()) {
			System.out.println("****swf转换器开始工作,该文件已经转换为 swf****");
			return true;
		}
		if (getOs() == 1) {
			System.out.println("****swf转换器开始工作,当前设置运行环境 windows****");
		} else {
			System.out.println("****swf转换器开始工作,当前设置运行环境 linux****");
		}
		try {
			doc2pdf();
			pdf2swf();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		System.out.println("文件存在吗?" + swfFile);
		if (swfFile.exists()) {
			System.out.println("存在");
			return true;
		} else {
			System.out.println("不存在");
			return false;
		}
	}

	/**
	 * 返回文件路径
	 * 
	 * @param
	 */
	public String getswfPath() {
		if (this.swfFile.exists()) {
			String tempString = swfFile.getPath();
			tempString = tempString.replaceAll("\\\\", "/");
			System.out.println("最后文件路径为" + tempString);
			return tempString;
		} else {
			return "文件不存在";
		}
	}

	/**
	 * 设置输出路径
	 * 
	 * @param outputPath
	 */
	public void setOutputPath(String outputPath) {
		this.outputPath = outputPath;
		if (!outputPath.equals("")) {
			String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
			if (outputPath.charAt(outputPath.length()) == '/') {
				swfFile = new File(outputPath + realName + ".swf");
			} else {
				swfFile = new File(outputPath + realName + ".swf");
			}
		}
	}
}
 
 
2).DocumentUtil
package com.classnet.util;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

public class DocumentUtil {

	/**
	* 文档工具类,根据上传的文件生成pdf和swf文件。
	* @param request
	* @param url
	*/
	public static void topdfAndswf(HttpServletRequest request,String url){
	String path = request.getRequestURI();
	File f = new File(path+url);
	if (f != null) {
	String tomcatURL_1 =request.getSession().getServletContext().getRealPath("/");
	String tomcatURL_2 = tomcatURL_1.replaceAll("\\\\", "/");
	//调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
	DocConverterUtil d = new DocConverterUtil(tomcatURL_2+url);
	//调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
	d.conver();
	}
	}
}
 
3).引入upload
4).引用
path = this.getServlet().getServletContext().getRealPath("/upload");
		FormFile file = clazzForm.getFile();
		if(file!=null&&file.getFileSize()>0){
			UploadFileImpl uploadFile = new UploadFileImpl(path+"/files",filesize,type,file);
			uploadFile.save(DateUtil.getDateString());
			entity.setFilename(uploadFile.getUploadFileName());
			//上传成功,同步生成pdf和swf文件
			//调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
			DocConverterUtil d = new DocConverterUtil(path+"/files/"+uploadFile.getUploadFileName());//上传成功的文件夹路径 
			//调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
			d.conver();
		}
 
 
5.前台
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<link href="<%=request.getContextPath()%>/css/flexpaper.css"
	rel="stylesheet" type="text/css" />
	<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqueryeeeee.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/flexpaper_flash.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/flexpaper_flash_debug.js"></script>
 
<div id="viewerPlaceHolder" class="flexpaper_viewer"
									style="width:630px;height:670px;text-align:center;"></div>
    
 <script type="text/javascript">
		var filename = $("#filename").val();
		if (filename != "") {
			var pos = filename.lastIndexOf(".");
			filename = filename.substring(0, pos);
			filename = filename + ".swf";
		}
		console.log(filename);
		var url =  "<%=basePath%>upload/files/" + filename;
		console.log(url);
		
		 var fp=new FlexPaperViewer('<%=basePath%>js/FlexPaperViewer','viewerPlaceHolder',{config:{SwfFile:escape(url),
				Scale : 1.2,
				ZoomTransition : 'easeOut',
				ZoomTime : 0.5,
				ZoomInterval : 0.2,
				FitPageOnLoad : false,
				FitWidthOnload : false,
				FullScreenAsMaxWindow : false,
				ProgressiveLoading : false,
				MinZoomSize : 0.2,
				MaxZoomSize : 5,
				SearchMatchAll : false,
				InitViewMode : 'SinglePage',
				RenderingOrder : 'flash',
				ViewModeToolsVisible : true,
				ZoomToolsVisible : true,
				NavToolsVisible : true,
				CursorToolsVisible : true,
				SearchToolsVisible : true,
				localeChain : 'en_US'
			}
		});
	</script>
 

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

附件列表