package shop.alien.util.openoffice;

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.OpenOfficeDocumentConverter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 自动启动本地openoffice服务 使doc,xls,ppt转换成PDF
 * 
 */

public class LocallinkToPDF {
	public static int office2PDF(String sourceFile, String destFile) {
		// 这里是OpenOffice的安装目录,C:\Program Files (x86)\OpenOffice 4
		System.out.println("寻找服务...");
		String OpenOffice_HOME = "C:/Program Files (x86)/OpenOffice 4/";
		// 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是尽对没题目的
		// 假如从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'
		if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '/') {
			OpenOffice_HOME += "/";
		}
		Process pro = 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();
			}
			// 启动OpenOffice的服务
			String command = OpenOffice_HOME + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;StarOffice.ServiceManager\" -nofirststartwizard";
			System.out.println("启动服务...");
			pro = Runtime.getRuntime().exec(command);
			// connect to an OpenOffice.org instance running on port 8100
			System.out.println("链接服务...");
			OpenOfficeConnection connection = new SocketOpenOfficeConnection("192.168.3.103", 8100);
			// OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
			connection.connect();

			// convert
			DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
			System.out.println("开始转换");
			converter.convert(inputFile, outputFile);
			// converter.convert(inputFile,xml,outputFile,pdf);

			// close the connection
			connection.disconnect();
			// 封闭OpenOffice服务的进程
			pro.destroy();

			return 0;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return -1;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			pro.destroy();
		}

		return 1;
	}

	public static void main(String[] args) throws Exception {
		String sourceFile = "D:\\MyTest\\file\\1.xls";
		String destFile = "D:\\1.pdf";
		LocallinkToPDF.office2PDF(sourceFile, destFile);
		System.out.println("转换完成");
	}
}