码迷,mamicode.com
首页 > 其他好文 > 详细

openOffice和SWFTools 在线浏览

时间:2015-06-18 11:35:25      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:openoffice   swftools   浏览器   转换文件   

简单介绍一下以下代码整体思路 :

1:为实现在线浏览阅读文档内容,首先要转换office 文档成pdf格式,在转换成swf,返回swf流就能实现在线浏览器形式阅读(图片可直接返回流,不用转换)

2:该代码未编写完全(要转换的类型未编写,写了个大概),只实现了我所用的需求,同时转换返回是否成功转换状态。

3:该代码实现了自动启动服务,无需担心关机重启服务忘记开启转换不了的情况(配置文件需要放在根目录下)

package com.mw.usims.fts.util;
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 com.ml.cs.Server;
import org.apache.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ConnectException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by LiAnAn on 2015/6/11.
 */
public class NewFileConvertUtil implements Callable<Integer> {
    private static Logger log = Logger.getLogger(NewFileConvertUtil.class);
    private File inputFile;
    private File outputFile;
    private int success = -1; // 0:成功 else 失败
    private String endType;
    private String beginType;
    private static boolean isStartServer = false;
    private static final String processName = "soffice.exe";
    private static String SWFTools_HOME;
    private static String openOffice_INSTALL_PATH;
    public NewFileConvertUtil(File inputFile,File outputFile,ConvertType type){
        initializeConfig();
        this.inputFile = inputFile;
        this.outputFile = outputFile;
        this.beginType = getType(type.toString(), SubStringType.PREFIX);
        this.endType = getType(type.toString(), SubStringType.SUFFIX);
    }

    /**
     * 初始化配置
     */
    private void initializeConfig(){
        if(null==SWFTools_HOME || null==openOffice_INSTALL_PATH){
            SAXReader reader = new SAXReader();
            String filePath = this.getClass().getResource("/")+"install-path-config.xml";
            //String filePath = Server.getContext().getServerHome().getAbsolutePath()+"install-path-config.xml";
            Document document = null;
            try {
                document = reader.read(filePath);
                Element element = document.getRootElement();
                openOffice_INSTALL_PATH = element.elementText("openOffice");
                SWFTools_HOME = element.elementText("SWFTools");
            } catch (DocumentException e) {
                e.printStackTrace();
            }

        }
    }

    public NewFileConvertUtil(File inputFile,File outputFile){
        initializeConfig();
        this.inputFile = inputFile;
        this.outputFile = outputFile;
        this.beginType = getFileType(inputFile);
        this.endType = getFileType(outputFile);
    }

    private String getType(String type,SubStringType subStringType){
        int len = type.indexOf("_");
        if(SubStringType.PREFIX.equals(subStringType)){
            return type.substring(0,len);
        }
        if(SubStringType.SUFFIX.equals(subStringType)){
            return type.substring(len + 1, type.length());
        }
        return null;
    }

    @Override
    public Integer call() throws Exception {
        run();
        return this.success;
    }

    enum SubStringType{
        PREFIX,
        SUFFIX;
    }


    enum  ConvertType{
        DOT_PDF,
        HTML_PDF,
        PPTX_PDF,
        DOCX_PDF,
        TXT_PDF,
        XLSX_PDF,
        DOC_PDF,
        PDF_SWF;
    }

    private boolean startSofficeProcess(){
        if(!isStartServer) {
            if (!isExistSofficeProcess()) {
                log.info("********************start soffice.exe process begin******************");
                String command = openOffice_INSTALL_PATH + "\\program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
                try {
                    log.info("Execute command"+command);
                    Process pro = Runtime.getRuntime().exec(command);
                } catch (IOException e) {
                    log.info("启动soffice.exe进程异常:(提示:异常1,配置openOffice安装目录异常;异常2,本机未安装openOffice应用程序;异常3,该文件类型不支持转换)", e) ;
                    return false;
                }
                log.info("********************start soffice.exe process end******************");
            }
        }
        return true;
    }

    private boolean isExistSofficeProcess(){
        String[] command = new String[]{"cmd.exe", "/C","wmic process get name" };
        int a=0;
        try {
            log.info("******* 获取所有进程名称判断soffice.exe是否存在 begin *******");
            Process pro = Runtime.getRuntime().exec(command);
            InputStream inputStream = pro.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String temp;
            while((temp=br.readLine())!=null){
                if(processName.equals(temp.trim())){
                    isStartServer = true;
                    a=1;
                    break;
                }
            }
            if(null!=br)br.close();
            if(null!=inputStream)inputStream.close();

        } catch (IOException e) {
            log.error("获取所有进程名判断是否存在soffice.exe异常:",e);
        }
        if(a==1){
            log.info("soffice.exe进程已存在,无需重新创建!");
        }else{
            log.info("创建soffice.exe进程成功!");
        }
        log.info("******* 获取所有进程名称判断soffice.exe是否存在 end *******");
        return isStartServer;
    }

    void convertPDF(){
        log.info("********************* 转换文件开始********************");
        if(startSofficeProcess()) {
            OpenOfficeConnection connection;
            try {
                connection = new SocketOpenOfficeConnection(8100);
                if(!connection.isConnected()) {
                    connection.connect();
                }
                DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
                converter.convert(inputFile, outputFile);
            } catch (ConnectException ce) {
                log.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"--转换文件异常:",ce);
                return;
            }
            success = 0;
            connection.disconnect();
        }
        log.info("********************* 转换文件结束********************");
    }

    void convertSWF() throws IOException {
        if(!outputFile.exists()){
            if(outputFile.isDirectory() || !inputFile.exists()){
                return;
            }
            if(outputFile.isFile()){
                outputFile.createNewFile();
            }
        }
        if(!inputFile.exists()){
            return ;
        }
        log.info("************* "+beginType+" begin*********************");
        String command = SWFTools_HOME + "\\pdf2swf.exe " + inputFile.getAbsolutePath() + " -o " + outputFile.getAbsolutePath() + " -T 9  ";
        log.info("Execute command:"+command);
        Process pro = Runtime.getRuntime().exec(command);
        try {
            pro.waitFor();
        } catch (InterruptedException e) {
            log.error("转换swf异常(提示:异常1,SWFTolls程序未安装;异常2,SWFTools安装目录未配置):",e);
        }
        log.info("************* "+beginType+"转换swf end*********************");
        success = pro.exitValue();
    }

    /**
     * 删除目录下所有文件、目录以及目录下文件
     * @param file
     * @return
     */
    public static boolean removeFile(File file){
        if(file.isDirectory()){
            String[] strings = file.list();
            for(int i=0;i<strings.length;i++){
                boolean success = removeFile(new File(file,strings[i]));
                if(!success){
                    return false;
                }
            }
        }
        file.delete();
        return true;
    }

    /**
     * 获取大写的文件后缀名
     * @param file
     * @return
     */
    private String getFileType(File file){
        String fileName = file.getName();
        return fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()).toUpperCase();
    }


    public synchronized void run() {
        try {
            Thread.sleep(10000);
            if(endType!=null){
                if("PDF".equals(endType)) {
                    convertPDF();
                }
                if("PDF".equals(beginType) && "SWF".equals(endType)){
                    convertSWF();
                }
            }else{
                log.info("转换的文件类型和ConvertType不匹配,无法转换程序停止运行");
                return;
            }
        } catch (InterruptedException e) {
            log.error("转换pdf异常:",e);
        } catch (IOException e) {
            log.error("转换SWF异常:",e);
        }
    }

    public static List<Integer> execute(List<NewFileConvertUtil> task){
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<Integer>> list = new ArrayList<>(task.size());
        for(int i=0;i<task.size();i++){
            list.add(exec.submit(task.get(i)));
        }
        ArrayList<Integer> results = new ArrayList<>(task.size());
        for(Future<Integer> fs : list){
            try {
                results.add(fs.get().intValue());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        if(!exec.isShutdown()){
            exec.shutdown();
        }
        return results;
    }

    public static Integer execute(File inputFile,File outputFile) {
        ExecutorService exec = Executors.newCachedThreadPool();
        NewFileConvertUtil convert = new NewFileConvertUtil(inputFile,outputFile);
        Future<Integer> fs = exec.submit(convert);

        try {
            return fs.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            if(!exec.isShutdown()){
                exec.shutdown();
            }
        }
        return -1;
    }

    public static void main(String arg0[]) throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();
        NewFileConvertUtil convert = new NewFileConvertUtil(new File("E:\\51job_宋庆亨(86307153).doc"),new File("E://123456.pdf"));
        Future fs = exec.submit(convert);
        System.out.println(fs.get());
        if(!exec.isShutdown()){
            exec.shutdown();
        }

    }
}

下面是配置文件,放到根目录下,会自动加载

<?xml version="1.0" encoding="UTF-8"?>
<main>
    <common>程序安装路径配置</common>
    <openOffice>C:\Program Files (x86)\OpenOffice 4</openOffice>
    <SWFTools>C:\Program Files (x86)\SWFTools</SWFTools>

</main>


openOffice和SWFTools 在线浏览

标签:openoffice   swftools   浏览器   转换文件   

原文地址:http://blog.csdn.net/an74520/article/details/46544927

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!