在java中如何使用openOffice进行格式转换,word,excel,ppt,pdf互相转换

1.首先需要下载并安装openOffice,下载地址为: Apache OpenOffice download | SourceForge.net

2.安装后,可以测试下是否可用;

3.build.gradle中引入依赖:

implementation group: 'com.artofsolving', name: 'jodconverter', version: '2.2.1'
implementation group: 'com.github.livesense', name: 'jodconverter-core', version: '1.0.5'
implementation group: 'org.jodconverter', name: 'jodconverter-local', version: '4.4.2'

4.创建工具类,启动openOffice服务的方法

    private static OfficeManager officeManager;
    private static int port[] = {8100};
/**
     * start openOffice service.
     */
    public void startService() {
        DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
        try {
            System.out.println("准备启动office转换服务....");
            configuration.setOfficeHome("这里的路径一般为C:\\Program Files (x86)\\OpenOffice 4");// 设置OpenOffice.org安装目录
            configuration.setPortNumbers(port); // 设置转换端口,默认为8100
            configuration.setTaskExecutionTimeout(1000 * 60 * 30L);// 设置任务执行超时为30分钟
            configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 设置任务队列超时为24小时
            officeManager = configuration.buildOfficeManager();
            officeManager.start(); // 启动服务
            System.out.println("office转换服务启动成功!");
        } catch (Exception e) {
            System.out.println("office转换服务启动失败!详细信息:" + e);
        }
    }

5.结束openOffice服务的方法

 /**
     * stop openOffice service.
     */
    public void stopService() {
        System.out.println("准备关闭office转换服务....");
        if (officeManager != null) {
            officeManager.stop();
        }
        System.out.println("office转换服务关闭成功!");
    }

7.在测试方法中进行格式转换,如,他可以是任意类型转换,如excel转换为pdf,word转换为pdf,只需要你传入一个任意类型文件,输出一个任意类型文件即可。

    public void convertToPDF(String inputFile, String outputFile){
        startService();
        System.out.println("进行文档转换转换:" + inputFile + " --> " + outputFile);
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        converter.convert(new File(inputFile), new File(outputFile));
        stopService();
    }

效果预览:

xlsx转换前效果:

在java中如何使用openOffice进行格式转换,word,excel,ppt,pdf互相转换_第1张图片

 转换为pdf后效果:

在java中如何使用openOffice进行格式转换,word,excel,ppt,pdf互相转换_第2张图片

 

你可能感兴趣的:(java,openOffice,springboot)