`
zcz123
  • 浏览: 151034 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类

利用openoffice进行各种格式转换为PDF

 
阅读更多

参考:https://blog.csdn.net/liumiaocn/article/details/73480915

openoffice有window和linux版本,通过安装openoffice软件,在java里头进行调用它来实现各种格式的转换,

核心代码如下

/**
	 * 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice下载地址为
	 * http://www.openoffice.org
	 * <pre>
	 * 方法示例:
	 * window系统下
	 * String sourcePath = "F:\\office\\source.doc";
	 * String destFile = "F:\\pdf\\dest.pdf";
	 * Office2PDF.office2PDF(sourcePath, destFile);
	 * linux系统下
	 * String sourcePath = "/office/source.doc";
	 * String destFile = "/pdf/dest.pdf";
	 * Office2PDF.office2PDF(sourcePath, destFile);
	 * </pre>
	 * @param sourceFile
	 *            源文件, 绝对路径. 可以是Office2003-2007全部格式的文档
	 *            包括.doc,.docx, .xls, .xlsx, .ppt, .pptx等
	 * @param destFile
	 *            目标文件. 绝对路径.
	 * @return 操作成功与否的提示信息. 
	 * 		         如果返回 -1,表示找不到源文件
	 * 		         如果返回 0 ,表示转换失败
	 *         如果返回 1 ,表示操作成功
	 */
	public static int office2PDF(String sourceFile, String destFile) {
		Process pro = null;
		OpenOfficeConnection connection = null;
		try {
			File inputFile = new File(sourceFile);
			if (!inputFile.exists()) {
				return -1;// 找不到源文件, 则返回-1
			}
			// 如果目标路径不存在, 则新建该路径
			File outputFile = new File(destFile);
			if (!outputFile.getParentFile().exists()) {
				outputFile.getParentFile().mkdirs();
			}
			String OpenOffice_HOME = OPEN_OFFICE_HOME;
			if (OpenOffice_HOME == null || OpenOffice_HOME =="") {
				return -1;
			}
			
			String separator = System.getProperty("file.separator");
			if (OpenOffice_HOME.substring(OpenOffice_HOME.length()-1) != separator) {
				OpenOffice_HOME += separator;
			}
			String sofficeProgram = "/".equals(separator)?"soffice":"soffice.exe";
			// 启动OpenOffice的服务
			String ooProgram = "program" + separator + sofficeProgram + " -headless -accept=\"socket,host=%s,port=%s;urp;\" -nofirststartwizard";
			String command = OpenOffice_HOME + String.format(ooProgram, OPEN_OFFICE_IP,OPEN_OFFICE_PORT);
			pro = Runtime.getRuntime().exec(command);
			connection = new SocketOpenOfficeConnection(OPEN_OFFICE_IP, Integer.parseInt(OPEN_OFFICE_PORT));
			connection.connect();
			//调用openoffice转换格式类进行转换
			DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
			converter.convert(inputFile, outputFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return -1;
		} catch (ConnectException e) {
			e.printStackTrace();
			return 0;
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}finally {
			//关闭连接
			if(connection != null && connection.isConnected()) {
				connection.disconnect();
			}
			// 关闭OpenOffice服务的进程
			if(pro != null) {
				pro.destroy();
			}
		}
		return 1;
	}

 在window上进行转换速度正常,字体也正常,linux下会乱码需要拷贝字体到/usr/share/fonts下来解决乱码问题,速度上很慢,目前还没有找到解决方案,需要依赖的包,参考如下pom.xml的配置


 

  • 大小: 53.1 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics