Office转换pdf(oppenOffice和jodconverter-core-3.0-beta-4)解决并发问题

转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/94783897 谢谢

Office转换pdf解决并发问题

由于项目之前的代码 https://blog.csdn.net/Amor_Leo/article/details/89389321
不能支持并发 于是用了锁机制和阻塞队列实现
方法 一 :

@Component
public class Office2PDFUtils {

    private static Logger logger = LoggerFactory.getLogger(Office2PDFUtils.class);

    @Value("${oppenOffice.winPath}")
    private String winPath;
   
    @Value("${oppenOffice.linuxPath}")
    private String linuxPath;

    @Value("${oppenOffice.port}")
    private String port;

    private static BlockingQueue<OfficeManager> OfficeManagerQueue = new LinkedBlockingDeque<>();

    private static Lock lock = new ReentrantLock();

    /**
     * @Description: 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件
     * @method: openOfficeToPDF
     * @Param: inputFilePath
     * @Param: outputFilePath
     * @return: boolean
     * @auther: LHL
     */
    public boolean openOfficeToPDF(String inputFilePath, String outputFilePath) {
        return office2Pdf(inputFilePath, outputFilePath);
    }

    /**
     * @Description: 根据操作系统的名称,获取OpenOffice.org 的安装目录
     * @method: getOfficeHome
     * @Param:
     * @return: java.lang.String OpenOffice.org 的安装目录
     * @auther: LHL
     */
     private String getOfficeHome() {
        String osName = System.getProperty("os.name");
        logger.debug("操作系统名称:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return linuxPath;
        } else if (Pattern.matches("Windows.*", osName)) {
            return winPath;
        } else if (Pattern.matches("Mac.*", osName)) {
            return winPath;
        }
        return null;
    }
  
    /**
     * @Description: 在bean创建实例时, 连接OpenOffice.org 并且启动OpenOffice.org
     * @method: initOpenOfficeService
     * @Param:
     * @return: void
     * @auther: LHL
     */
    @PostConstruct
    public void initOpenOfficeService() {
        DefaultOfficeManagerConfiguration builder = new DefaultOfficeManagerConfiguration();
        builder.setOfficeHome(getOfficeHome());        
        //设置任务执行超时为15分钟
        builder.setTaskExecutionTimeout(1000 * 60 * 15L);
        //设置任务队列超时为24小时
        builder.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        for (String port : port.split(",")) {
            builder.setPortNumbers(Integer.valueOf(port));
            OfficeManager OfficeManager = builder.buildOfficeManager();
            try {
                OfficeManager.start();
                logger.debug("***********************officeManager 启动!***********************");
            } catch (OfficeException e) {
                //打印日志
                logger.debug("***********************启动 openOffice 失败!***********************");
                e.printStackTrace();
            }
            try {
                OfficeManagerQueue.put(OfficeManager);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Description: bean销毁时停止
     * @method: destroyOpenOfficeService
     * @Param:
     * @return: void
     * @auther: LHL
     */
    @PreDestroy
    public void destroyOpenOfficeService() {
        for (OfficeManager manager : OfficeManagerQueue) {
            try {
                logger.debug("关闭 officeManager");
                manager.stop();
            } catch (OfficeException e) {
                logger.debug("officeManager关闭失败!" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * @Description: 转换文件
     * @method: convertFile
     * @Param: inputFile
     * @Param: outputFilePath
     * @Param: officeManager
     * @return: java.io.File
     * @auther: LHL
     */
    private File convertFile(File inputFile, String outputFilePath, OfficeManager officeManager) throws OfficeException {
        File outputFile = new File(outputFilePath);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        // 锁
        lock.lock();
        converter.convert(inputFile, outputFile);
        //释放锁
        lock.unlock();
        try {
            OfficeManagerQueue.put(officeManager);
            logger.debug("blockingQueue puted OfficeManagerQueue size :" + OfficeManagerQueue.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.debug("文件:" + inputFile.getAbsolutePath() + "\n转换为目标文件:" + outputFile + "\n成功!");
        return outputFile;
    }
	/**
	* 文件名需要唯一
	*/
    public boolean office2Pdf(String inputFilePath, String outputFilePath) {
        OfficeManager officeManager = null;
        try {
            if (StringUtils.isEmpty(inputFilePath)) {
                logger.debug("输入文件地址为空,转换终止!");
                return false;
            }
            File inputFile = new File(inputFilePath);
            if (!inputFile.exists()) {
                logger.debug("输入文件不存在,转换终止!");
                return false;
            }
            officeManager = OfficeManagerQueue.take();
            logger.debug("blockingQueue taked , OfficeManagerQueue size :" + OfficeManagerQueue.size());
            File file = convertFile(inputFile, outputFilePath, officeManager);
            if (!file.exists()) {
                logger.debug("转换文件不存在!转换失败!!");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("转换异常");
            return false;
        }
    }
}

方法 二 :
初始化OpenOffice

@Component
public class InitOpenOfficeUtil {

    private static Logger logger = LoggerFactory.getLogger(InitOpenOfficeUtil.class);

    @Value("${oppenOffice.winPath}")
    private String winPath;
    @Value("${oppenOffice.linuxPath}")
    private String linuxPath;
    @Value("${oppenOffice.port}")
    private String port;

    private static BlockingQueue<OfficeManager> OfficeManagerQueue = new LinkedBlockingDeque<>();
    /**
     * @Description: 根据操作系统的名称,获取OpenOffice.org 的安装目录
     * @method: getOfficeHome
     * @Param:
     * @return: java.lang.String OpenOffice.org 的安装目录
     * @auther: LHL
     */
    private String getOfficeHome() {
        String osName = System.getProperty("os.name");
        logger.debug("操作系统名称:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return linuxPath;
        } else if (Pattern.matches("Windows.*", osName)) {
            return winPath;
        } else if (Pattern.matches("Mac.*", osName)) {
            return winPath;
        }
        return null;
    }

    /**
     * @Description: 在bean创建实例时, 连接OpenOffice.org 并且启动OpenOffice.org
     * @method: initOpenOfficeService
     * @Param:
     * @return: void
     * @auther: LHL
     */
    @PostConstruct
    public void initOpenOfficeService() {
        DefaultOfficeManagerConfiguration builder = new DefaultOfficeManagerConfiguration();
        builder.setOfficeHome(getOfficeHome());
        //设置任务执行超时为15分钟
        builder.setTaskExecutionTimeout(1000 * 60 * 15L);
        //设置任务队列超时为24小时
        builder.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        for (String port : port.split(",")) {
            builder.setPortNumbers(Integer.valueOf(port));
            OfficeManager OfficeManager = builder.buildOfficeManager();
            try {
                OfficeManager.start();
                logger.debug("***********************officeManager 启动!***********************");
            } catch (OfficeException e) {
                //打印日志
                logger.debug("***********************启动 openOffice 失败!***********************");
                e.printStackTrace();
            }
            try {
                OfficeManagerQueue.put(OfficeManager);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Description: bean销毁时停止
     * @method: destroyOpenOfficeService
     * @Param:
     * @return: void
     * @auther: LHL
     */
    @PreDestroy
    public void destroyOpenOfficeService() {
        for (OfficeManager manager : OfficeManagerQueue) {
            try {
                logger.debug("关闭所有 officeManager");
                manager.stop();
            } catch (OfficeException e) {
                logger.debug("officeManager 关闭 失败!" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public  OfficeManager  take(){
        OfficeManager take = null;
        try {
            take = OfficeManagerQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return take;
    }

    public  void  put(OfficeManager officeManager){
        try {
            OfficeManagerQueue.put(officeManager);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public  int  size(){
        return  OfficeManagerQueue.size();
    }

OppenOffice工具类

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)  //多例
public class Office2PDFUtils {

    private static Logger logger = LoggerFactory.getLogger(Office2PDFUtils.class);

    @Autowired
    private InitOpenOfficeUtil initOpenOfficeUtil;

    /**
     * @Description: 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件
     * @method: openOfficeToPDF
     * @Param: inputFilePath
     * @Param: outputFilePath
     * @return: boolean
     * @auther: LHL
     */
    public boolean openOfficeToPDF(String inputFilePath, String outputFilePath) {
        return office2Pdf(inputFilePath, outputFilePath);
    }


    /**
     * @Description: 转换文件
     * @method: convertFile
     * @Param: inputFile
     * @Param: outputFilePath
     * @Param: officeManager
     * @return: java.io.File
     * @auther: LHL
     */
    private File convertFile(File inputFile, String outputFilePath, OfficeManager officeManager) throws OfficeException {
        File outputFile = new File(outputFilePath);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.convert(inputFile, outputFile);
        initOpenOfficeUtil.put(officeManager);
        logger.debug("blockingQueue puted OfficeManagerQueue size :" + initOpenOfficeUtil.size());
        logger.debug("文件:" + inputFile.getAbsolutePath() + "\n转换为目标文件:" + outputFile + "\n成功!");
        return outputFile;
    }

    /**
     * 文件名需要唯一
     */
    public boolean office2Pdf(String inputFilePath, String outputFilePath) {
        OfficeManager officeManager = null;
        try {
            if (StringUtils.isEmpty(inputFilePath)) {
                logger.debug("输入文件地址为空,转换终止!");
                return false;
            }
            File inputFile = new File(inputFilePath);
            if (!inputFile.exists()) {
                logger.debug("输入文件不存在,转换终止!");
                return false;
            }
            officeManager = initOpenOfficeUtil.take();
            logger.debug("blockingQueue taked , OfficeManagerQueue size :" + initOpenOfficeUtil.size());
            File file = convertFile(inputFile, outputFilePath, officeManager);
            if (!file.exists()) {
                logger.debug("转换文件不存在!转换失败!!");
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("转换异常");
            initOpenOfficeUtil.put(officeManager);
            logger.debug("blockingQueue puted OfficeManagerQueue size :" + initOpenOfficeUtil.size());
            return false;
        }
    }
}

yml

#配置OpenOffice的目录
oppenOffice:
  winPath: D:/SoftWare/OpenOffice
  linuxPath: /usr/local/OpenOffice
  port: 9200,9201,9202,9203,9204,9205,9206,9207,9208,9209

pom

<!-- 该依赖是自己上传到自己本地的maven仓库里  -->
		<dependency>
			<groupId>org.artofsolving.jodconverter</groupId>
			<artifactId>jodconverter-core</artifactId>
			<version>3.0-beta-4</version>
		</dependency>
		
		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>juh</artifactId>
			<version>4.1.2</version>
		</dependency>

		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>jurt</artifactId>
			<version>4.1.2</version>
		</dependency>

		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>ridl</artifactId>
			<version>4.1.2</version>
		</dependency>

		<dependency>
			<groupId>org.openoffice</groupId>
			<artifactId>unoil</artifactId>
			<version>4.1.2</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值