[测评系统]--测评系统核心代码库
林致杰
2023-02-14 6c71ce2454f7def4e4c247987ec7daf6971b8eba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.ots.project.tool.libreoffice;
 
import org.jodconverter.local.JodConverter;
 
import java.io.File;
 
/**
 * @version 1.0
 * @Author linzhijie
 * @Description //TODO
 * @Date 2023/02/14 0:21
 */
public class LibreOfficeUtil {
 
    /*
     * 同步转换
     * @Date    2021年11月09日 11:41:04
     * @Param   [sourceFile, targetFile]
     * @Return  boolean
     */
    public static boolean convertOffice2PDFSyncIsSuccess(File sourceFile, File targetFile) {
        try {
            OfficeManagerInstance.start();
            JodConverter.convert(sourceFile).to(targetFile).execute();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    /**
     * 利用 LibreOffice 将 Office 文档转换成 PDF,该转换是异步的,返回时,转换可能还在进行中,转换是否有异常也未可知
     * @param filePath       目标文件地址
     * @param targetFilePath 输出文件夹
     * @return 子线程执行完毕的返回值
     */
    public static int convertOffice2PDFAsync(String filePath, String fileName, String targetFilePath) throws Exception {
        String command;
        int exitStatus;
        String osName = System.getProperty("os.name");
        String outDir = targetFilePath.length() > 0 ? " --outdir " + targetFilePath : "";
 
        if (osName.contains("Windows")) {
            command = "cmd /c cd /d " + filePath + " && start soffice --headless --invisible --convert-to pdf ./" + fileName + outDir;
        } else {
            command = "libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + filePath + fileName + outDir;
        }
 
        exitStatus = executeOSCommand(command);
        return exitStatus;
    }
 
    /**
     * 调用操作系统的控制台,执行 command 指令
     * 执行该方法时,并没有等到指令执行完毕才返回,而是执行之后立即返回,返回结果为 0,只能说明正确的调用了操作系统的控制台指令,但执行结果如何,是否有异常,在这里是不能体现的,所以,更好的姿势是用同步转换功能。
     */
    private static int executeOSCommand(String command) throws Exception {
        Process process;
        process = Runtime.getRuntime().exec(command); // 转换需要时间,比如一个 3M 左右的文档大概需要 8 秒左右,但实际测试时,并不会等转换结束才执行下一行代码,而是把执行指令发送出去后就立即执行下一行代码了。
 
        int exitStatus = process.waitFor();
 
        if (exitStatus == 0) {
            exitStatus = process.exitValue();
        }
 
        // 销毁子进程
        process.destroy();
        return exitStatus;
    }
 
}