package cn.base.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

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;
/**
 * 利用jodconverter(基于OpenOffice服务)将文件(*.doc、*.docx、*.xls、*.ppt)转化为html格式或者pdf格式，
 * 使用前请检查是否已安装OpenOffice服务                 OpenOffice进程名称：soffice.exe | soffice.bin
 * 
 * @author yjclsx
 */
public class Doc2HtmlUtil {
 
	static String OPEN_OFFICE_IP = "127.0.0.1";
	static String OPEN_OFFICE_PORT = "8100";
	static String OpenOffice_HOME = "E:\\openOffice";
   
  /**
   * 
   * @param fromFileInputStream			文件输入流
   * @param toFilePath					生成的文件路径
   * @param type						文件类型     一般为  .doc/.docx/.xls/.xlsx/ppt
   * @param changeType					转换的文件类型     一般为 .pdf/.html
   * @return							返回的文件名
   * @throws IOException
   */
  public static String file2Html(InputStream fromFileInputStream, String toFilePath,String type,String changeType) throws IOException {
   
	  Process pro = null;
	  OpenOfficeConnection connection = null;
	  try {
		  Date date = new Date();
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		    String timesuffix = sdf.format(date);
		    String docFileName = timesuffix + type;
		    String htmFileName = timesuffix + changeType;
		    /*if("doc".equals(type)){
		      docFileName = "doc_" + timesuffix + ".doc";
		      htmFileName = "doc_" + timesuffix + ".html";
		    }else if("docx".equals(type)){
		      docFileName = "docx_" + timesuffix + ".docx";
		      htmFileName = "docx_" + timesuffix + ".html";
		    }else if("xls".equals(type)){
		      docFileName = "xls_" + timesuffix + ".xls";
		      htmFileName = "xls_" + timesuffix + ".html";
		    }else if("ppt".equals(type)){
		      docFileName = "ppt_" + timesuffix + ".ppt";
		      htmFileName = "ppt_" + timesuffix + ".html";
		    }else{
		      return null;
		    }*/
		 
		    File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName);
		    File docInputFile = new File(toFilePath + File.separatorChar + docFileName);
		    if (htmlOutputFile.exists())
		      htmlOutputFile.delete();
		    htmlOutputFile.createNewFile();
		    if (docInputFile.exists())
		      docInputFile.delete();
		    docInputFile.createNewFile();
		    
		    
		     // 由fromFileInputStream构建输入文件		     
		    OutputStream os = new FileOutputStream(docInputFile);
		    int bytesRead = 0;
		    byte[] buffer = new byte[1024 * 8];
		    while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
		        os.write(buffer, 0, bytesRead);
		    }
		 
		    os.close();
		    fromFileInputStream.close();
		    
		    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();
			
		    // convert
		    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
		    converter.convert(docInputFile, htmlOutputFile);
		    // 转换完之后删除word文件
		    docInputFile.delete();
		    return htmFileName;
	  }catch (IOException e) {
		  e.printStackTrace();
	  }finally {
			//关闭连接
			if(connection != null && connection.isConnected()) {
				connection.disconnect();
			}
			// 关闭OpenOffice服务的进程
			if(pro != null) {
				pro.destroy();
			}
		}
	return null;
  }
 
  
 
  public static void main(String[] args) throws IOException {
    File file = null;
    FileInputStream fileInputStream = null;
 
    String infile = "D:\\logback\\字段对比.xlsx";
	String tarFile = "D:\\logback\\字段对比.pdf";
	File targetFile = new File(tarFile);
	
		long start = System.currentTimeMillis();
		file = new File("D:\\logback\\字段对比.xlsx");
	    fileInputStream = new FileInputStream(file);
	    Doc2HtmlUtil.file2Html(fileInputStream, "D:\\logback",".xlsx",".html");
	    long end = System.currentTimeMillis();
	    System.out.println("总共耗时："+(end-start));
	
  }
 
}
