使用openoffice软件将office文档转换成pdf

支持linux和windowx的转pdf的java程序,当然服务器端需要安装不同版本的OpenOffice;
private static OpenOfficeConnection connection = null;

	public static void officeToPdf(File srcFile, File destFile) {
		try {
			// 这里是OpenOffice的安装目录,
			String sysIp ="127.0.0.1";//获取系统IP
			String OOPath = "D:\\OpenOffice.org 3\\program\\soffice.exe -headless -accept=\"socket,host\=127.0.0.1,port\=8100;urp;\"";// 获取系统OpenOffice的安装目录,linux下:/opt/OpenOffice.org3/program/soffice -headless -accept\="socket,host\=127.0.0.1,port\=8100;urp;
			// 启动OpenOffice的服务
			Process pro = null;
			try {
				pro = Runtime.getRuntime().exec(OOPath);
			} catch (IOException e) {
				e.printStackTrace();
			}
			OpenOfficeConnection connection = getConnection(sysIp);
			DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
			String fileExt = "";
			String fileName = srcFile.getName();
			int i = fileName.indexOf(".");
			if (i != -1) {
				fileExt = fileName.substring(i + 1);
			}
//不同版本的office文档
			if ("wps".equalsIgnoreCase(fileExt)) {
				DocumentFormat df = new DocumentFormat("Kingsoft wps", DocumentFamily.TEXT, "application/wps", "wps");
				DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
				DocumentFormat pdf = formatReg.getFormatByFileExtension("pdf");
				converter.convert(srcFile, df, destFile, pdf);
			} else if ("et".equalsIgnoreCase(fileExt)) {
				DocumentFormat df = new DocumentFormat("Kingsoft et", DocumentFamily.TEXT, "application/et", "et");
				DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
				DocumentFormat pdf = formatReg.getFormatByFileExtension("pdf");
				converter.convert(srcFile, df, destFile, pdf);
			} else if ("dps".equalsIgnoreCase(fileExt)) {
				DocumentFormat df = new DocumentFormat("Kingsoft dps", DocumentFamily.TEXT, "application/dps", "dps");
				DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
				DocumentFormat pdf = formatReg.getFormatByFileExtension("pdf");
				converter.convert(srcFile, df, destFile, pdf);
			} else {
				converter.convert(srcFile, destFile);
			}
			String osname = System.getProperty("os.name");
			if (osname.indexOf("Windows") > -1) {
				connection.disconnect();
			} else {
				connection.connect();
			}
			pro.destroy();
		} catch (ConnectException e) {
			logger.error("officeToPdf error:", e);
		} catch (Exception e) {
			logger.error("officeToPdf error:", e);
		}
	}

	private static OpenOfficeConnection getConnection(String sysIp) throws ConnectException {
		if (connection == null || !connection.isConnected()) {
			connection = new SocketOpenOfficeConnection(sysIp, 8100);
			connection.connect();
		}
		return connection;
	}

	public static void main(String[] s) {
		File office = new File("D:\\test.doc");
		File pdf = new File("D:\\test.pdf");
		ConvertX2PDFHelper.officeToPdf(office, pdf);
	}

猜你喜欢

转载自xlxin.iteye.com/blog/2085295